Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template tags {{for/empty}} for loop variable

To generate a set of Javascript variables with the relevant parameters from my Django application I have two nested for loops:

<script>
{% for model in models %} 
    {% for item in model.attribute|slice:":3" %}
        {% if forloop.first %} 
            var js_variable{{ forloop.parentloop.counter0 }} = [
        {% endif %}
            '{{ item.attribute }}' ,
        {% if forloop.last %}
            {{ item.attribute }} ]
    {% empty %}
        var js_variable{{ forloop.parentloop.counter0 }} = []
    {% endfor %}
{% endfor %}

....code that gets unhappy when js_variable[n] doesn't exist.....

</script>

When {% empty %} occurs it doesn't seem to have the access to the {{ forloop.parentloop. counter0 }} variable, and so the variable name js_variable[n] is printed incorrectly as js_variable (without the number otherwise provided by the counter), and later code complains.

Is it the case that this variable won't be available in the {{ empty }} tag?

like image 306
mrmagooey Avatar asked Mar 12 '12 12:03

mrmagooey


People also ask

What does {{ this }} mean in Django?

{{ foo }} - this is a placeholder in the template, for the variable foo that is passed to the template from a view. {% %} - when text is surrounded by these delimiters, it means that there is some special function or code running, and the result of that will be placed here.

Which Django template syntax allows to use the for loop?

To create and use for loop in Django, we generally use the “for” template tag. This tag helps to loop over the items in the given array, and the item is made available in the context variable.

What does {% endblock %} mean?

{% endblock %} </div> </body> </html> In this example, the {% block %} tags define four blocks that child templates can fill in. All the block tag does is tell the template engine that a child template may override those portions of the template.

What characters surround the template tag in Django?

Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .


1 Answers

This is an expected behavior. Simplifying we have:

{% for A ... %}
    {{ forloop.* }} is there for the 'for A ...'

    {% for B ... %}
        {{ forloop.* }} is there for the 'for B ...'
        {{ forloop.parentloop.* }} refers to the 'for A ...'
    {% empty %}
        {{ forloop.* }} is there for the 'for A ...' !!!
    {% endfor %}
{% endfor %}

In {% empty %}, {{ forloop }} refers to the parent forloop! Change:

var js_variable{{ forloop.parentloop.counter0 }} = []

With:

var js_variable{{ forloop.counter0 }} = []
like image 197
jpic Avatar answered Sep 30 '22 17:09

jpic