views:

194

answers:

1

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  A: 

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")
Brian Luft