Putting a block inside another in Django

非 Y 不嫁゛ 提交于 2019-12-06 05:35:18

问题


I have a Django template that I want to extend in multiple places. In some the div must be inside a form, and in others it must not be. To do this I put a block above and below the div so I could add and in them respectively.

Desired:

<form>
<div class="my_div">
  {% block div_content %}
    ...
  {% endblock %}
</div>
</form>

Template:

{% block div_top %}{% endblock %}
<div class="my_div">
  {% block div_content %}
  {% endblock %}
</div>
{% block div_bottom %}{% endblock %}

Looking at this I can't help but think that there is a better way to do it. What is the standard Django way of doing this?


回答1:


Use of multiple base templates is a solution I've seen a few teams use. For example, you might just add an additional base template called "base_with_form.html". Templates that need the form extend this base template.

One thing that has helped me is to think of laying out template directories in a manner similar to Python packages. I typically include a base.html per directory (ala init.py) even if it is just a placeholder. Every base file extends a base file in its parent directory. Additional specializations of styles for multiple templates in the same directory are accomplished by adding copies of the local base.html with the desired changes.

Ex:

templates/
  base.html
  index.html (extends "base.html")
  accounts/
    base.html (extends "base.html")
    affiliate_base.html (extends "base.html")
    my_account.html (extends "accounts/base.html")
    affiliate_dashboard.html (extends "accounts/affiliate_base.html")
    vips/
      base.html (extend "accounts/base.html")
      vip_lounge.html (extends "accounts/vips/base.html")


来源:https://stackoverflow.com/questions/2437123/putting-a-block-inside-another-in-django

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