【问题标题】:Django template language include variableDjango 模板语言包含变量
【发布时间】:2015-03-12 04:28:17
【问题描述】:

include documentation 中,他们声明您可以将模板包含在变量中。但是他们没有解释如何编写模板变量。

我想做类似的事情:

{% variable thing %}
  <div> Hello {{name}} </div>
{% endvariable thing %}

{# include the variables #}
{% include thing with name='Chris' %}
{% include thing with name='Julie' %}

【问题讨论】:

  • 所以您的模板上下文中有一个名为“thing”的键,它的模板路径类似于“foo/bar.html”?您必须在视图中添加它。
  • 我编的变量关键字,因为我不知道怎么做。我想将模板包含在同一个文件中,而不是另一个文件中。我意识到我可以将我的模板放在一个单独的 html 文件中并将其包含在另一个文件中。我试图避免这样做,因为变量 thing 将在一个文件中使用
  • 您误读了文档。它说您可以使用从变量中获取的名称来包含模板文件,而不是模板内容可以在变量中。

标签: django django-templates


【解决方案1】:

只需创建模板thing.html

<div>Hello {{name}}</div>

然后在主模板中包含它:

{% include 'thing.html' with name='Chris' %}
{% include 'thing.html' with name='Julie' %}

【讨论】:

【解决方案2】:

对于您的示例,您需要在视图中的模板上下文中添加一个名为“thing”的键。 'thing' 需要一个像“foo/bar.html”这样的值,一个模板的路径。

return render_to_response('index.html', {
    'thing': 'foo/bar.html'}, RequestContext(request))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 1970-01-01
    • 2018-11-09
    • 1970-01-01
    相关资源
    最近更新 更多