Django:无法将变量传递给包含的模板?

duy*_*duy 7 django templates django-templates

我遇到了一个问题,我想在Django中使用模板.

这是一个真实的例子:我有3个文件:

  • home.html(将获取从Views传递的上下文变量)
  • base.html(骨架模板文件)
  • header.html(由base.html包含).

如果我将以下代码直接放在base.html中而不包含header.html,则会正确调用从home传递的{{title}}变量.但是,如果我包括了header.htmlbase.html文件,{{title}}的变量的值不能被调用.

<title>{% block title %}{% endblock %} | {{ SITE_INFO_TITLE }}</title>
Run Code Online (Sandbox Code Playgroud)

有没有解决这个问题的方法?谢谢.

The*_*pes 11

你能在{% include %}标签内传递一个变量吗?它在此处记录:https://docs.djangoproject.com/en/1.5/ref/templates/builtins/#include

{% include "name_snippet.html" with person="Jane" greeting="Hello" %}
Run Code Online (Sandbox Code Playgroud)


VGE*_*VGE 4

据我所知,django 中的块和变量是不同的。如果您想将标题作为上下文变量传递,则必须使用 base.html 中的声明来设置它,例如:

{% include "header.html"%} 
Run Code Online (Sandbox Code Playgroud)

其中又包含:

{% block title %} {{title}} {%endblock%}
Run Code Online (Sandbox Code Playgroud)

家里也可以这样设置。
{% block title %} 主页 {%endblock%} 但我也尝试在模板上下文中设置。没有标题栏。

def test_view(ctx):
  xa = { "title":"Sommaire"}
  return render_to_response("test.html",xa)
Run Code Online (Sandbox Code Playgroud)

我想您还可以看到with模板标签,我认为可以使用此标签设置上下文变量。