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

To generate a set of Javascript variables with the appropriate parameters from my Django application, I have two nested 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 does not have access to the {{ forloop.parentloop. counter0 }} {{ forloop.parentloop. counter0 }} , so the variable name js_variable[n] incorrectly printed as js_variable (without the number provided by another counter) and later code complains.

Is it possible that this variable will not be available in the {{ empty }} tag?

+4
source share
1 answer

This is the expected behavior. Simplification:

 {% 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 }} = [] 

FROM

 var js_variable{{ forloop.counter0 }} = [] 
+6
source

Source: https://habr.com/ru/post/1400988/


All Articles