[Django]-Django template includes

16👍

Generally, using includes is not the answer with Django templates. Let me answer your question on several fronts.

First, let me address the sidebar.

  • Are nearly all the common pages going to be using that sidebar? Put it in Base. Don’t override those sidebar blocks (i.e. don’t write them at all in your Story_* templates).

  • Is this sidebar unique to the Story_* templates? Make another template called, say, Story_base and extend that. This is akin to making an abstract superclass in Java. (Answer was in my head, but wording was mercilessly ripped off from jpwatts.)

Next, let me address template inheritance. Say you have a template named Story_list that extends Base. At this point, after just putting {% extends "Base" %}, Story_list is exactly Base. Anything else you put in Story_list is ignored, because the template is already complete. The only thing you can do now is override blocks that have been defined in Base.

Finally, let me address includes. Try to always avoid them. Other templating engines, such as PHP, seem to encourage using includes. However, this can lead to less manageable templates in the long run. It’s slightly harder to glance at an included snippet and immediately ascertain its place in your template hierarchy. They’re also harder to refactor into the template hierarchy, especially if you include them at several levels (once in Base, twice in Story_base, once in some of the Story_*, etc.).

👤Wesley

6👍

If there is common code between the story templates that isn’t needed site-wide, I’d create a story_base (extending the original base) and have my story templates extend that.

0👍

You have an {% include %} tag for this.

👤S.Lott

0👍

{% include xxx.html %}

This tag works.

An alternative way is to use filter. Filter calls a function for rendering, template can be used while rendering.

Leave a comment