【发布时间】:2018-05-05 05:19:35
【问题描述】:
我希望一个模板使用 Django {% include %} 标记从另一个模板继承变量。但它没有发生。
section.html,要继承的模板:
{% block section1 %}
<p>My cows are home.</p>
--> {{ word_in_template }} <--
{% endblock %}
index.html,应该从section.html继承word_in_template:
{% 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。但我是新来的,所以也许我读错了东西或其他东西。我做错了什么?
【问题讨论】:
-
请注意
render_to_response已过时,您应该改用render。 -
块在您使用模板继承来扩展另一个模板时很有用,例如
{% extends 'base.html' %}。当您使用{% include %}时,您没有使用模板继承,因此在您的section.html模板中包含{% block section1 %}是没有意义的。 -
也感谢这些!