最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Django template tags {{forempty}} for loop variable - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Mar 12, 2012 at 13:22 jpic 33.4k5 gold badges113 silver badges114 bronze badges asked Mar 12, 2012 at 12:58 mrmagooeymrmagooey 4,9827 gold badges39 silver badges49 bronze badges 0
Add a comment  | 

1 Answer 1

Reset to default 17

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 }} = []
发布评论

评论列表(0)

  1. 暂无评论