在Django中包含模板。我做得对吗?

时间:2015-07-17 18:24:02

标签: django templates include

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

我的方法:
渲染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正文元素添加内容):

<p>Hallo World!</p>

views.py(根据请求呈现index.html):

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

问题:
我的方法正在发挥作用,但我对此并不自信。特别是分开头部和身体部位感觉不对。有没有更好的方法呢?我如何避免将include_head.html与include_body.html一起使用,而是使用单个include.html?

1 个答案:

答案 0 :(得分: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>