How to use Django template as a component?

北城余情 提交于 2019-12-13 03:13:12

问题


I have 5 templates: index.html, detail.html, tag.html, login.html, register.html and a base.html

All 5 templates will extend base.html.

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.

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

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

Any good way to solve this question in Django?


回答1:


EDIT

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>

Wherever you want the section, just include section.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 %}

ORIGINAL ANSWER

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

Consider base.html:

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

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

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

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

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

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 %}



回答2:


You can have multiple base templates. For example:

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


来源:https://stackoverflow.com/questions/51779319/how-to-use-django-template-as-a-component

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!