把一个模板分成几个部分并把每个部分都包括进去是不是不好?

2024-04-26 02:29:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个基本模板,我想分成三部分:页眉,正文,页脚。然后我使用基本模板来包含这三个子模板。然而,根据我所见,这意味着我不能覆盖{block}}内容。那么使用包括坏主意吗?或者有没有办法覆盖包含的模板中的块内容?在

我知道您可以向包含的段发送静态上下文变量,但它需要更动态。在

我的代码:

在页眉.html在

<html>
    <head>
        <script url="..."></script>
        <link rel="..." />
        {% block head_extension %}

        {% endblock %}
    </head>
    <body>
        <header>
            <div class="headerstuff">
            </div>
        </header>

然后在正文.html文件:

^{pr2}$

在页脚.html公司名称:

        <footer>
            {% block footer %}
                Copyright 2015
            {% endblock %}
        </footer>
    </body>
</html>

在基本.html公司名称:

{% include "header.html" %}
{% include "body.html" %}
{% include "footer.html" %}
<!-- and the part that doesn't work -->
{% block head_extension %}
    <script src="unique_script"></script>
{% endblock %}
{% block content %}
    My unique content
{% endblock %}
{% block footer %}
    Copyright 2011
{% endblock %}
<!-- end broken django templating try -->

我做错什么了吗?模板文档似乎表明我所要做的不起作用。这似乎是创建易于阅读的模板的最佳方法。把所有的部分放在一个大文件里比较好吗?可以想象,header、body和footer元素比这个演示要大得多。但问题依然存在。在

我希望有一种方法可以做我所不知道的事情。在

提前谢谢


Tags: div模板内容includehtmlextensionscriptbody
1条回答
网友
1楼 · 发布于 2024-04-26 02:29:29

你的方法很好,但你做的顺序不对。首先,html的起始<html>和结束标记</html>不应分割成不同的文件,最好将其放在base.html中。在

下面是如何遵循分解结构的示例:

基本.html

<html>
    <head>
        <!  Some stuff here which should be included in all templates for example js or css  >
        {% block extra_css %}
            <!  to included app-template dependent css  >
        {% endblock extra_css %}

        {% block extra_js %}
            <!  to included app-template dependent js  >
        {% endblock extra_js %}

        {% block extra_head %}
            <!  for anything else inside head  >
        {% endblock extra_head %}

    </head>
    <body>
        {% block menu %}
            <!  Default menu here  >
            {% block extra_menu %}
                <!  extend menu based on template  >
            {% endblock extra_menu %}
        {% endblock menu %}

        {% block content %}
            <div>This is good</div>
        {% endblock content %}

        {% include "footer.html" %}

        {% block bottom_js %}
            <!  if you want to have manual js scripts at bottom  >
        {% endblock bottom_js %}
    </body>
</html>

现在base.html是所有设置现在让我们假设从另一个子模板,你想覆盖base.html块{}你将要做的:

儿童.html

^{pr2}$

因此,当页面加载时,您将看到this is really good,而不是{}(它是在基本.html在内容块内)因为你只是重写它。在

如果您想保留base.html中内容块内的任何内容,则需要扩展该块,而不是使用方法{{ block.super }}完全重写它

儿童.html

^{3}$

现在您将看到this is good和{}。希望这能澄清你的概念,对你有好处。在

相关问题 更多 >

    热门问题