如何使用Django模板作为组件? [英] How to use Django template as a component?

查看:97
本文介绍了如何使用Django模板作为组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

All 5 templates will extend base.html.

index.html,详细信息.html,tags.html 具有相同的< section> ...< / section> html代码段,并具有来自后端的相同数据。将该部分添加到 base.html 中,这样就不必在3个不同的模板中重复3次。

index.html, detail.html, tags.html have a same <section>...</section> html code section with the same data from backend.I want to add this section to base.html, so that don't need to repeat it 3 times in 3 different templates.

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

But the problem is,the login.html and register.html do need this section.

我知道它是React.js还是Vue.js。

I know if it is React.js or Vue.js it will be very easy to use component to solve it.

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

Any good way to solve this question in Django?

推荐答案

编辑

正如评论中提到的OP,要求与我的要求有很大不同可以解释。因此,根据我的较新理解,可以使用的修复程序就是 {%include'section.html'%} ,如沉沧仪的评论

As the OP mentioned in the comments, the requirements are quite different from what I could interpret. Thus, the fix that can be used based on my newer understanding is simply {% include 'section.html' %} as aptly pointed out in Tsang-Yi Shen's comment.

base.html

<!-- HTML here.... -->
{% block normal_content %}{% endblock %}

section.html

<section>
<!-- Special Section -->
</section>

无论您想查看该部分,只需添加 section.html

Wherever you want the section, just include section.html

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

login.html and all others which require the special section:

{% extends "base.html" %}
{% block normal_content %}
    Hey There!
    {% block section %}
        {% include 'section.html' %}
    {% endblock %}
{% endblock %}

原始答案

塞尔柱克的答案很好地解释了这个概念。我通过提供代码示例以供将来参考来补充该答案。

Selcuk's answer explains the concept beautifully. I am adding to that answer by providing code examples for future reference.

考虑 base.html

<!-- HTML here.... -->
<!-- Common Section -->
{% block section %}{% endblock %}
{% block normal_content %}{% endblock %}
<!-- End Common Section -->

现在为您的栏目使用模板, baseWithSection.html

Now use a template for your section, baseWithSection.html:

{% extends 'base.html' %}
{% block section %}
<section>
....
</section>
{% endblock %}
{% block special_content %}{% endblock %}

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

For all pages that do not contain the section, extend base.html like so:

{% extends 'base.html' %}
{% block normal_content %}
<!-- HTML here... -->
{% endblock %}

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

For the pages that do require the section, extend section.html like so:

{% extends 'baseWithSection.html' %}
{% block special_content %}
<!-- Special HTML here, for templates pages requiring the section -->
{% endblock %}

这篇关于如何使用Django模板作为组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆