gpt4 book ai didi

python - Django,如何在许多模板中使用 render_to_response

转载 作者:太空宇宙 更新时间:2023-11-03 13:43:48 26 4
gpt4 key购买 nike

你好,我是 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 中的内容显示良好,我只能看到页面上的空白区域如果我把模板 1:

return render_to_response('template1.html', {

它只加载来自 main 和 template1.html 的内容,但我需要来自 template2.html 的内容

如果我让 template2.html 起作用,它只显示来自 main.html 和来自 template2.html 的内容,但没有来自 template1.html 的内容请帮我解决这个问题。

最佳答案

选项 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>

在你的 View / Controller 中:

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 %}

在你的 View / Controller 中:

return render_to_response('projects/detail.html', {

关于python - Django,如何在许多模板中使用 render_to_response,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24615711/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com