I have base.html template like this:
<p>{% block a %}{% endblock %}</p>
<p>{% block b %}{% endblock %}</p>
And index.html template:
{% extends "base.html" %}
{% with description="foo" %}
{% block a %}{{ description }}{% endblock %}
{% block b %}{{ description }}{% endblock %}
{% endwith %}
But the result becomes:
<p></p>
<p></p>
Instead of:
<p>foo</p>
<p>foo</p>
Is there any workaround for this?
Not in the way you'd like it to, in inherited templates django looks for code inside of blocks
which means it won't recognize the existence of your with
block outside of this. so your only option is to include the with inside each block
{% block a %}
{% with description="foo" %}
{{ description }}
{% endwith %}
{% endblock %}
Although for a single call it isn't worth using the with
, the only other option is to pass description
through the context
UPDATE: It doesn't work as I expected for my particular case. See comments.
After reading Sayse's answer and understanding better how blocks work, I've come with this solution:
base.html:
{% block wrapping_block %}
{% block a %}
{% endblock %}
{% block b %}
{% endblock %}
{% endblock %}
index.html:
{% extends "base.html" %}
{% block wrapping_block %}
{% with description='foo' %}
{% block a %}
{{ description }}
{% endblock %}
{% block b %}
{{ description }}
{% endblock %}
{% endwith %}
{% endblock %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With