0

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

section.html,要继承的模板:

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

index.html,它应该继承word_in_templatesection.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})

section.html在 Chrome 中的输出:

My cows are home.

--> frisky things. <--

index.html在 Chrome 中的输出:

My cows are home.

--> <--

我正在遵循这个解决方案,但它对我不起作用。"frisky things"显示我是否加载section.html但它没有显示在index.html. 但是,硬编码的字符串My cows are home显示在index.html.

我想我也正在关注文档。但我是新来的,所以也许我读错了东西或其他东西。我究竟做错了什么?

4

1 回答 1

1

当您包含section.htmlindex.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 %}
于 2017-11-21T16:51:45.393 回答