Override inner template block in Django
I have the following structure of templates (simplified for clarity):
base1.html:
<html>
<head>{% block head %}{% endblock %}</head>
<body>{% block body %}{% endblock %}</body>
</html>
base2.html:
{% extends "base1.html" %}
{% block head %}
<meta .... />
<title .... />
css includes etc.
{% endblock %}
{% block body %}
{% block header %}{% endblock %}
{% block featured %}{% endblock %}
{% block navigation %}{% endblock %}
{% block content %}{% endblock %}
{% block footer %}{% endblock %}
{% endblock %}
Also base3.html and base4.html which futher detalize the generic body structure defined in previous bas开发者_JAVA百科e templates (not shown here). The last template extends base4.html, overriding blocks with concrete content (markup is handled by base templates).
The question is: I have two templates: main.html and article.html which both extend base4.html. But in article.html I want the order of body blocks defined in base2.html to be different (featured block to go after navigation). How can I achieve that? Or how to refactor the structure of templates to make this possible? Overriding the block body in top-level template doesn't work.
I don't think that you're going to have any luck going about it that way. A simple solution could be to have an optional variable that base2.html looks at, which determines the alternate order. In fact it may even be that you can define the presence of this variable in the article.html template itself. I haven't tried this, but something like the following may work:
{% with alternate_order=1 %}
{% include base4.html
{% endwith %}
Why do you have so many levels of inheritance? As a note, django provides no limitations, but typically we use the three-level approach. See docs
Here are a few suggestions:
- You can probably combine base1.html and base2.html.
- If you can put the html code in the parent then do so. I usually implement my templates like this:
<div id='sidebar'>{% block sidebar_content %}{% endblock %}</div>
As for your problem, if you need a different layout, that's when you branch. That is, if using a different css won't work.
精彩评论