Django,如何使用render_to_response与多个模板?

3
你好,我是 Django 的新手,今天开始学习它,但在模板继承方面遇到了问题。我的视图中有这样一个函数:
def show(request, id=1):

return render_to_response('template1.html', {
    'name': name,
    'model1': Model1.objects.get(id=id),
    'model2': Model2.objects.get(id=id).model1,
})

我有3个不同的模板,其中主要的是main.html,代码如下:
<body>
{% block block1 %}
{% endblock %}
{% block block2 %}
{% endblock %}
</body>
</html>

"还有两个包含类似代码的模板:"
{% extends 'main.html' %}
{% block block1 %}
    <h2>{{ var }}</h2>
    <pre>{{ var }}</pre>
{% endblock %}

第二个很相似,所以我不会展示它,问题是:我不知道应该放哪一个在render_to_response函数中。 如果我放main.html:
 return render_to_response('main.html', {

它没有加载任何模板,但是来自main.html的内容显示正常,我只能看到页面上的空白空间。如果我放置template1:
return render_to_response('template1.html', {

它只从主文件和template1.html加载内容,但我需要从template2.html加载内容。
如果我将template2.html放入函数中,它只会显示来自main.html和template2.html的内容,但没有来自template1.html的内容。请帮助我解决这个问题。
1个回答

6

选项1) 尝试使用{% include %}标签。


main.html

<head> ... </head>
<body>
{% block content %}
{% endblock content %}

template1.html

{% extends "main.html" %}
{% block content %}
     <h1>Hello world</h1>
     {% include "nested_template2.html" %}
{% endblock content %}

nested_template2.html

<p>The world is smaller than you think.</p>

在你的视图/控制器中:

return render_to_response('template1.html', {

选项2)将{% extends ... %}标签链式嵌套,您可以根据需要进行多层次的嵌套。我经常使用以下结构:
templates/
----base.html
----projects/
    ----_.html
    ----detail.html
    ----list.html

base.html是主要的页面布局。而folder/_.html则是特定于某一“阶段”的模块化内容。


base.html

<head> ... </head>
<body>
{% block stage_content %}
{% endblock stage_content %}

projects/_.html

{% extends "main.html" %}
{% block stage_content %}
     <h1>Project Stage</h1>
     {% block page_content %}
     {% endblock page_content %}
{% endblock stage_content %}

projects/list.html

{% extends "projects/_.html" %}

{% block page_content %}
   {% for project in projects %}
       <li>{{ project.name }}</li>
   {% endfor %}
{% endblock page_content %}

projects/detail.html

{% extends "projects/_.html" %}

{% block page_content %}
   Viewing project {{ project.name }}
{% endblock page_content %}

在你的视图/控制器中:
return render_to_response('projects/detail.html', {

我不喜欢这样,我需要将一个模板包含到另一个模板中,你确定没有更简单的解决方案吗? - user2757588
我添加了另一个选项。 - pztrick
非常感谢您的想法,我稍后会将答案标记为解决方案,也许我会得到更多选项,所以我会等待一下。谢谢。 - user2757588

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接