Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to repeat a "block" in a django template
    text
    copied!<p>I want to use the same <strong>{% block %}</strong> twice in the same django template. I want this block to appear more than once in my base template:</p> <pre><code># base.html &lt;html&gt; &lt;head&gt; &lt;title&gt;{% block title %}My Cool Website{% endblock %}&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;{% block title %}My Cool Website{% endblock %}&lt;/h1&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>And then extend it:</p> <pre><code># blog.html {% extends 'base.html' %} {% block title %}My Blog{% endblock %} # pictures.html {% extends 'base.html' %} {% block title %}My Pictures{% endblock %} # cats.html {% extends 'base.html' %} {% block title %}My Cats{% endblock %} </code></pre> <p>I will get an exception, as Django wants the block to appear only once:</p> <blockquote> <p><strong>TemplateSyntaxError at /</strong></p> <p><strong>'block' tag with name 'title' appears more than once</strong></p> </blockquote> <p>A quick and dirty solution would be duplicating the block <em>title</em> into <em>title1</em> and <em>title2</em>:</p> <pre><code># blog.html {% extends 'base.html' %} {% block title1 %}My Blog{% endblock %} {% block title2 %}My Blog{% endblock %} </code></pre> <p>But this is a violation of the <a href="http://docs.djangoproject.com/en/dev/misc/design-philosophies/#don-t-repeat-yourself-dry" rel="noreferrer">DRY</a> principle. It would be very difficult as I have a lot of inheriting templates, and also because I don't wanna go to hell ;-)</p> <p>Is there any trick or work-around to this problem? How can I repeat the same block in my template, without duplicating all the code?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload