[Solved]-Django Template inheritance: how many levels and what page to render

8đź‘Ť

It’s hard to say if it’s a good or bad idea or not without knowing the specific functionality of your templates, but my immediate reaction is that you’re trying to over organize your templates. I think most people would urge you away from more than a 3-tier system because it makes it more difficult to make small changes in the website and more difficult to keep track of where things are. from the Zen of Python:

Flat is Better than Nested

The recommendation for a 3-tier system inTwo Scoops of Django goes like this:

  1. Each app has a base_<app_name>.html template. App-level base templates share a common parent, base.html.
  2. Templates within apps share a common parent base_<app_name>.html template.
  3. Any template at the same level as base.html inherits base.html

and for your naming schema, it might look like this:

  | Templates/
  |--base.html
  |--someothertemplate.html # extends base.html
  |--level2/
  |----base_level2.html     # extends base.html
  |----level2_1.html        # extends base_level2.html
  |----level2_2.html        # extends base_level3.html

EDIT: and there’s no real reason for this:

    Second level
   {% block level3_1 %}{% endblock %}
   {% block level3_2 %}{% endblock %}

where each block refers to the content of one template. you can simplify that to one block like

{% block level3 %}{% endblock level3%}

and then in each of the level3 templates, rename the blocks accordingly

👤skzryzg

3đź‘Ť

Probably not the best way of doing it but you might user include https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include

something like this for base_level2.html

{% extends "base.html" %}
{% block level2 %}
Second level
{% include "level2_level3_1.html" %}   
{% include "level2_level3_2.html" %} 
{% endblock %}

i’ve not tested this, so not sure it works.

and btw:

The include tag should be considered as an implementation of “render this subtemplate and include the HTML”, not as “parse this subtemplate and include its contents as if it were part of the parent”. This means that there is no shared state between included templates – each include is a completely independent rendering process.

👤EsseTi

Leave a comment