Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django nested 'with' and 'block' tag

Tags:

django

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?

like image 550
dablak Avatar asked Mar 13 '23 19:03

dablak


2 Answers

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

like image 119
Sayse Avatar answered Mar 28 '23 06:03

Sayse


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 %}
like image 25
dablak Avatar answered Mar 28 '23 06:03

dablak