【问题标题】:Is it okay to have two base.html templates in django?在 django 中有两个 base.html 模板可以吗?
【发布时间】:2022-01-10 05:34:12
【问题描述】:

django 中可以有多个 base.html 模板吗?例如,我将有一个从 base_one.html 扩展的模板和另一个从 base_two.html 扩展的模板。例如,这是模板之一:

{% extends "base_one.html" %}

{% block content %}
{% endblock content %}

这是另一个模板:

{% extends "base_two.html" %}

{% block content %}
{% endblock content %}

【问题讨论】:

  • 是的,完全没问题。

标签: django django-models django-views django-forms django-templates


【解决方案1】:

不仅是两个,您可以使用不同的名称保留所需的数量,并且您必须在不同的模板上进行扩展,但是是的,您可以轻松地保留部分基本模板并根据您的需要进行扩展。

我这里添加三个文件 1-base.html 2-base-cmets.html 3-post-template.html

这是我的答案的一点扩展 假设这个文件名是 base.html

# base.html
    <html>
        <head>
            <title>Foo</title>
        </head>
        <body>
            <header>
                {% block header %}
                    <h1>Lorem ipsum</h1>
                {% endblock %}
            </header>
            {% block content %}{% comment %}A wrapper around content is needed{% endcomment %}
                <div class="page-content">
                    {% block page_content %}{% comment %} Filled in by your page templates {% endcomment %}
                    {% endblock %}
                </div>
            {% endblock %}
            <footer>
                {% block footer %}
                    <em>&#x2665; joar</em>
                {% endblock footer %}
            </footer>
        </body>
    </html>

这是另一个文件base-cmets.html,它扩展了前一个文件。

# base-comments.html
    {% extends 'base.html' %}
    {% block content %}
        <div class="page-content">
            {% block page_content %}{% comment %} Filled in by your page templates {% endcomment %}
            {% endblock %}
            
            {% block comments %}
                <footer>
                    <h2>Comments</h2>
                    <script>loadCommentsEtc()</script>
                </footer>
            {% endblock %}
        </div>
    {% endblock %}

这是扩展第二个基本文件的最后一个文件,该文件已经扩展了第一个基本文件 3-post-template.html

# post-template.html
    {% extends 'base-comments.html' %}
    {% block page_content %}
        <article>
            <h1>{{ post.title }}</h1>
            <div class="post-body">
                {{ post.body }}
            </div>
        </article>
    {% endblock %}

我希望这能解决您的疑虑。 感谢您的提问。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-16
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多