Django {%include%}标签显示硬编码字符串但不是变量

时间:2017-11-21 16:41:53

标签: django django-inheritance

我希望一个模板使用Django {% include %}标记从另一个模板继承变量。但它没有发生。

section.html,继承自的模板:

{% block section1 %}
<p>My cows are home.</p>
--> {{ word_in_template }} <--
{% endblock %}

index.html,应该从word_in_template继承section.html

{% include "section.html" with word_in_template=word_in_template %}

我也试过{% include "section.html" with word_in_template=word %}

我的观点:

def myblog(request):
    return render_to_response('index.html')

def section(request):
    word = "frisky things."
    return render_to_response('section.html', {'word_in_template':word})

Chrome中section.html的输出:

My cows are home.

--> frisky things. <--

Chrome中index.html的输出:

My cows are home.

--> <--

我正在关注this solution,但它对我不起作用。 "frisky things"显示我是否加载了section.html,但未在index.html上显示。但是,硬编码字符串My cows are home会显示在index.html上。

我想我也正在关注documentation。但我是新人,所以也许我不是在读正确的东西。我做错了什么?

1 个答案:

答案 0 :(得分:1)

当您在section.html模板中加入index.html时,它不会自动包含section视图中的上下文。您需要在myblog视图中包含上下文。

def myblog(request):
    word = "my_word"
    return render(request, 'index.html', {'word_in_template':word}))

在模板中,执行include的正确方法是word_in_template=word_in_template,因为word_in_template是上下文字典中的键。

{% include "section.html" with word_in_template=word_in_template %}