Skip to main content
 首页 » 编程设计

python之Django 模板 {% block %} 标签中变量的使用

2025年05月04日25haluo1

主要问题是我如何以编程方式选择将某些内容放入哪个 block 。以下是在不同的项目中工作,但在新项目中由于某种原因这不起作用。我在同一台机器上为两个项目使用相同的(默认)模板上下文处理器。

我有一个像这样的基本模板

... 
{% block Title %}<h1>Whoo</h1>{% endblock %} 
 
{% block Content %}<p>Hi there</p>{% endblock %} 
... 

还有像这样的扩展模板

{% extends "base.html" %} 
... 
{% block myblock.name %} <p> {{ myblock.content }} </p> {% endblock %} 
 
<p> {{ myblock.name }} </br> {{ myblock.content }} </p> 
... 

这样渲染

myblock = { 'name': 'Title', 'content': 'stuff' } 
return render_to_response( 'extended.html', {'myblock': myblock}, context_instance=RequestContext(request) ) 

我希望得到并开始第一个项目:

... 
<p> stuff <p> 
<p>Hi there</p> 
<p> Title </br> stuff </p> 
... 

但是在第二个项目中我得到了

... 
<h1>Whoo</h1> 
<p>Hi there</p> 
<p> Title </br> stuff </p> 
... 

因此在第二个项目中,myblock dict 由模板传递和处理,但 {% block myblock.name %} 中的 myblock.name 似乎被解释为文字而不是变量。关于如何强制 Django 评估 {% block %} 标签内的变量有什么想法吗?

请您参考如下方法:

您应该再看一下有关 template inheritance 的文档.

... the block tag defines [...] blocks that child templates can fill in. All the block tag does is to tell the template engine that a child template may override those portions of the template.

但是您不会像您尝试的那样直接在 View 中将变量分配给 block 。

{% block myblock.name %} 看起来也很奇怪。

为了收到您期望的结果,我认为模板应该看起来像这样

{% extends "base.html" %} 
{% block Title %}<p>{{ myblock.content }}</p>{% endblock %} 

假设您使用的是最新版本的 Django,您甚至可以使用 render 来简化事情您 View 中的快捷方式:

return render(request, 'extended.html', {'name': 'Title', 'content': 'stuff'}) 

这将导致这样的模板:

{% extends "base.html" %} 
{% block Title %}<p>{{ content }}</p>{% endblock %}