【问题标题】:Custom counter in django templateDjango 模板中的自定义计数器
【发布时间】:2016-03-07 16:02:42
【问题描述】:

我在 django 模板页面中有这段代码

<select class="selectpicker datatable-column-control" multiple
{% for q_group in question_groups %}
    <optgroup label="{{ q_group.name }}">
    {% for q in  q_group.questions %}
        <option value="{{ forloop.counter0 }}">{{ q.title }}</option>
    {% endfor %}
    </optgroup>
{% endfor %}

我想要在每次迭代中增加的每个选项标签的值。如果我有 10 个选项标签,那么它们的值将是 0 到 9。 forloop.counter0 不能满足我的需要,因为当外循环完成一次时,内循环计数器初始化为 0。

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    itertools.count 对象传递给模板怎么样?

    模板:

    <select class="selectpicker datatable-column-control" multiple>
    {% for q_group in question_groups %}
        <optgroup label="{{ q_group.name }}">
        {% for q in  q_group.questions %}
            <option value="{{ counter }}">{{ q.title }}</option>
        {% endfor %}
        </optgroup>
    {% endfor %}
    </select>
    

    查看:

    import itertools
    import functools
    
    render(request, 'template.html', {
        question_groups: ...,
        counter: functools.partial(next, itertools.count()),
    })
    

    【讨论】:

      【解决方案2】:

      恢复这篇文章以提供仅使用模板语言的解决方案。

      如果您知道计数器之间只有一个{% for %}(如上例所示),请使用forloop.parentloop。您可以将其中的许多链接在一起,但必须知道分隔所需循环的循环数量,并且在几个之后使用它变得不太理想(forloop.parentloop.parentloop...)。

      {% for foo in foos %}
        {% for bar in bars %} {# exactly one for loop between here #}
          {{ forloop.parentloop.counter0 }} is the index of foo. 
        {% endfor %}
      {% endfor %}
      

      如果您在两者之间有任意数量的 for 循环(例如在您无法控制的模板或 django-crispy-forms 中),请使用 with statement 保存循环变量:

      {% for foo in foos %}
        {% with foo_num=forloop.counter0 %}
          {% for bar in bars %} {# any number of for loops between #}
            {{ foo_num }} is the index of foo. 
          {% endfor %}
        {% endwith %}
      {% endfor %}
      

      Falsetru 的解决方案最适合缺少 for 循环的计数器,或者在一个结束后继续计数的计数器。仅使用内置函数实际上无法实现此功能,因此 falsetru 答案中的 itertools 是必要的。

      {% for foo in foos %}
        {{ counter }} is the index of foo
      {% endfor %}
      {% for bar in bars %}
        {{ counter }} is the index of bar + len(foos)
      {% endfor %}
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        {% for foo in foos %}
            {{ forloop.counter0 }}
        {% endfor %}
        

        https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#for

        【讨论】:

          猜你喜欢
          • 2019-06-06
          • 1970-01-01
          • 2019-04-03
          • 1970-01-01
          • 2010-11-15
          • 1970-01-01
          • 2015-11-06
          • 2013-09-29
          • 2017-02-20
          相关资源
          最近更新 更多