为了使用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>当发生{% empty %}时,它似乎无法访问{{ forloop.parentloop. counter0 }}变量,因此变量名js_variable[n]被错误地打印为js_variable (没有计数器以其他方式提供的数字),并且后面的代码报告。
是不是这个变量在{{ empty }}标记中不可用?
发布于 2012-03-12 20:59:57
这是意料之中的行为。简化我们有:
{% 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 %}在{% empty %}中,{{ forloop }}引用了父forloop!更改:
var js_variable{{ forloop.parentloop.counter0 }} = []通过以下方式:
var js_variable{{ forloop.counter0 }} = []https://stackoverflow.com/questions/9667434
复制相似问题