【问题标题】:Django {% include %} tag displays hardcorded string but not variableDjango {% include %} 标签显示硬编码字符串但不可变
【发布时间】: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 %} 是没有意义的。
  • 也感谢这些!

标签: django django-inheritance


【解决方案1】:

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

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

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

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

【讨论】:

  • 这给了我一个 NameError,name 'word' is not defined。那么,我也必须将变量word = "frisky things." 添加到myblog 视图中?
  • 是的,如果你在上下文中包含word,你必须在视图中定义它。
  • 好的。只是澄清一下,因为我认为{% include %} 会使代码更加干燥。谢谢!
  • {% include %} 标签使您的模板更加干燥,它不会自动从其他视图中提取模板上下文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
  • 1970-01-01
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
相关资源
最近更新 更多