I’m having an issue with django templates at the moment. I have 3 template files basically:
- Base
- story_list
- story_detail
Story_list and _detail extend Base, and that works perfectly fine. However, list and detail share some code that extend the base template for my sidebar. I’m basically repeating a chunk of code in both templates, and the programmer in me says that’s just wrong. There has to be a better way, I’m sure of it. I’ve tried includes, however I have in the included file:
{% block item %}
content stuff
{% endblock %}
for about 3 blocks. The problem is that none of that is being picked up/rendered. If I include the file in a block section that extends base, then it dumps everything properly, but if I don’t include it in a block, I get nothing. Is SSI the way to go? I toyed with that, but that didn’t seem to work properly either. Any help is appreciated.
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 yourStory_*templates).Is this sidebar unique to the
Story_*templates? Make another template called, say,Story_baseand 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_listthat extendsBase. At this point, after just putting{% extends "Base" %},Story_listis exactlyBase. Anything else you put inStory_listis ignored, because the template is already complete. The only thing you can do now is override blocks that have been defined inBase.Finally, let me address
includes. Try to always avoid them. Other templating engines, such as PHP, seem to encourage usingincludes. 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 inBase, twice inStory_base, once in some of theStory_*, etc.).