mrm*_*oey 7 javascript python django
要使用我的Django应用程序中的相关参数生成一组Javascript变量,我有两个嵌套的for循环:
<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>
Run Code Online (Sandbox Code Playgroud)
当{% empty %}发生它似乎没有访问{{ forloop.parentloop. counter0 }}变量,因此变量名称js_variable[n]打印不正确js_variable(没有计数器提供的数字),以后代码抱怨.
是否这个变量在{{ empty }}标签中不可用?
这是预期的行为.简化我们:
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
在{%empty%}中,{{forloop}}指的是父forloop!更改:
var js_variable{{ forloop.parentloop.counter0 }} = []
Run Code Online (Sandbox Code Playgroud)
附:
var js_variable{{ forloop.counter0 }} = []
Run Code Online (Sandbox Code Playgroud)