如何使用 Django 模板作为组件?

Wil*_*iam 2 python django django-templates django-views

我有 5 个模板:index.html、detail.html、tag.html、login.html、register.html和base.html

所有 5 个模板都将扩展base.html。

index.html、detail.html、tags.html具有相同的<section>...</section>html 代码部分,来自后端的数据相同。我想将此部分添加到base.html 中,这样就不需要在 3 个不同的模板中重复 3 次.

但问题是,login.html 和 register.html确实需要这个部分。

我知道无论是 React.js 还是 Vue.js,使用组件来解决它会很容易。

有什么好方法可以在 Django 中解决这个问题?

sak*_*k21 6

编辑

正如评论中提到的 OP,要求与我可以解释的完全不同。因此,根据我较新的理解可以使用的修复方法{% include 'section.html' %}在Tsang-Yi Shen 的评论中恰如其分地指出。

base.html:

<!-- HTML here.... -->
{% block normal_content %}{% endblock %}
Run Code Online (Sandbox Code Playgroud)

section.html

<section>
<!-- Special Section -->
</section>
Run Code Online (Sandbox Code Playgroud)

无论您想要该部分的何处,只需包括 section.html

login.html 以及所有其他需要特殊部分的:

{% extends "base.html" %}
{% block normal_content %}
    Hey There!
    {% block section %}
        {% include 'section.html' %}
    {% endblock %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

原答案

Selcuk 的回答很好地解释了这个概念。我通过提供代码示例以供将来参考来添加该答案。

考虑base.html:

<!-- HTML here.... -->
<!-- Common Section -->
{% block section %}{% endblock %}
{% block normal_content %}{% endblock %}
<!-- End Common Section -->
Run Code Online (Sandbox Code Playgroud)

现在为您的部分使用模板baseWithSection.html:

{% extends 'base.html' %}
{% block section %}
<section>
....
</section>
{% endblock %}
{% block special_content %}{% endblock %}
Run Code Online (Sandbox Code Playgroud)

对于所有不包含该部分的页面,base.html像这样扩展:

{% extends 'base.html' %}
{% block normal_content %}
<!-- HTML here... -->
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

对于确实需要该部分的页面,请section.html像这样扩展:

{% extends 'baseWithSection.html' %}
{% block special_content %}
<!-- Special HTML here, for templates pages requiring the section -->
{% endblock %}
Run Code Online (Sandbox Code Playgroud)


Sel*_*cuk 5

您可以有多个基本模板。例如:

base.html            # Has the minimum shared elements
|
 -> base_page.html   # extends base.html (and adds your <section>...</section>)
|   |
|    -> index.html   # extends base_page.html
|    -> detail.html  # extends base_page.html
 -> login.html       # extends.base.html
 -> register.html    # extends.base.html
Run Code Online (Sandbox Code Playgroud)