Django template inheritance - How to use the same content for different blocks

advertisements

I've the following structure in my django templates

I've a theme_base.html which other templates inherit from:

[...]
&lttitle&gt{% block page_title_header %}{% endblock %}&lt/title&gt
[...]
&lth1&gt{% block page_title_body %}{% endblock %}&lt/h1&gt

Now, most pages have the same page_title for their header and base, so I need to do something like this in my normal templates:

{% block page_title_header %}Page title of current page{% endblock %}
{% block page_title_body %}Page title of current page{% endblock %}

This is not DRY and most of the times I forget to update page_title_header :(

Could you recommend a DRY way to pass the page title (of different each page, so I can't use a default value) to both blocks ?

Update: After a discussion in comments, I believe that the {% with %} template tag would be what I need to use, to do something like this:

{% with "Page title" as title %}
    {% block page_title_header %}{{ title }}{% endblock %}
    {% block page_title_body %}{{ title }}{% endblock %}
{% endwith %}

Unfortuanately, the above is not working, title is not passed to the block !! If I remove the {% block %} and do something like

{% with "Page title" as title %}
    Title is {{ title }}
{% endwith %}

it will work fine. Do you know what could be the problem ? TIA


You can specify a default value in your blocks, such as:

[...]
<title>{% block page_title_header %}Page title{% endblock %}</title>
[...]
<h1>{% block page_title_body %}Page title{% endblock %}</h1>

When you omit these blocks in your normal templates, default values will be used.