Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
-6
rated 0 times [  1] [ 7]  / answers: 1 / hits: 17360  / 12 Years ago, mon, march 12, 2012, 12:00:00

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?


More From » python

 Answers
7

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

[#86904] Saturday, March 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stephonkeandrer

Total Points: 392
Total Questions: 94
Total Answers: 100

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;