【问题标题】:Include Templates in Django. Am i doing it right?在 Django 中包含模板。我做对了吗?
【发布时间】:2015-10-07 13:25:32
【问题描述】:

问题:
我想将多个模板包含到另一个模板中,该模板最初会被渲染。

我的方法:
渲染 index.html,它扩展 base.html 并包含其他模板(include_body.html、include_head.html)

base.html:

<html>
    <head>
        {% block head %}{% endblock %}
    </head>
    <body>
        {% block body %}{% endblock %}
    </body>
</html>

index.html:

{% extends 'base.html' %}   
{% block head %}{% include 'include_head.html' %}{% endblock %}
{% block body %}{% include 'include_body.html' %}{% endblock %}

include_head.html(将内容添加到 HTML 头元素):

<script src="./static/js/map.js"></script>

include_body.html(将内容添加到 HTML body 元素):

<p>Hallo World!</p>

views.py(根据要求渲染 index.html):

# ...
def index(request):
    return render(request, 'index.html')

问题:
我的方法有效,但我对此没有信心。将头部和身体部分特别分开感觉是错误的。有更好的方法吗?如何避免将 include_head.html 与 include_body.html 一起使用,而是使用单个 include.html?

【问题讨论】:

    标签: django templates include


    【解决方案1】:

    这取决于你需要什么。我看到了 2 个案例:

    • 如果出于任何原因我可以拥有两个或多个基本模板(例如 base.html 和 base_mobile.html),它们必须共享某些部分(例如大多数信息),我会在 base_mobile 中执行此操作:李>
    <html>
        <head>
            <script src="./static/js/mobile.js"></script>
            {% include 'include_head.html' %}
        </head>
        ...
    </html>
    

    base.html 也一样,但不包含 mobile.js。

    • 如果 include_head 仅用于一个文件,我认为没有理由不将其内容直接写入该文件。
    <html>
        <head>
            <script src="./static/js/map.js"></script>
        </head>
        ...
    </html>
    

    【讨论】:

    • 感谢您的意见。总而言之,避免将我的 include_body.html 与 include_head.html 一起使用的一种方法是将 include_head.html 的内容直接写入 index.html。我最终只会使用一个包含正文内容的 include.html。无论如何这对我来说不是一个选项,因为我想动态地将内容添加到 index.html 中的 HTML 头元素。
    猜你喜欢
    • 2017-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-17
    • 1970-01-01
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    相关资源
    最近更新 更多