【问题标题】:Django, how to use render_to_response with many templatesDjango,如何将 render_to_response 与许多模板一起使用
【发布时间】:2014-07-07 16:48:45
【问题描述】:

你好,我是 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 的内容 请帮我解决这个问题。

【问题讨论】:

    标签: python django templates


    【解决方案1】:

    选项 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', {
    

    【讨论】:

    • 我不喜欢这样,我需要在另一个模板中包含一个模板,你确定没有更简单的解决方案吗?
    • 我添加了另一个选项。
    • 非常感谢您的想法,我稍后会将答案标记为解决方案,也许我会得到更多选择,所以我会等待。
    猜你喜欢
    • 2013-05-02
    • 1970-01-01
    • 2012-03-01
    • 2011-06-05
    • 2013-01-23
    • 2015-10-25
    • 2018-07-29
    • 2015-10-29
    • 1970-01-01
    相关资源
    最近更新 更多