【问题标题】:How to use array elements as labels using for loop in Template Django?如何在模板 Django 中使用 for 循环将数组元素用作标签?
【发布时间】:2012-07-04 05:29:09
【问题描述】:

我有以下模板代码,目前我正在获取循环计数器作为我的表单集的标签。我怎样才能得到数组'月'的元素(例如month.counter,其中计数器是循环)作为我的标签?我试过 {{month.forloop.counter}} 但没用

<html>

<head>
<title>Actuals</title>
</head>

<body>

<h1>Actuals Data</h1>

<h2>Your Account Number is : {{ Account_Number }}</h2>
<h2>You Chose {{ Year }} {{month}} as period.</h2>


{% if form.errors %}

    <p style="color: red;">
   Please correct the error{{ form.errors|pluralize }}below.</p>

   {% endif %}


<form action="." >
    {{ formset.management_form }}




<table>

      {% for form in formset %}

    {{form.id}}

            <div class="field">
                {{ form.Value.errors }}
                <label for="id_Value">{{months}}.{{forloop.counter}}</label>
                {{ form.Value }}
            </div>


      {% endfor %}

    </table>



</form>

    </body>

    </html>

【问题讨论】:

    标签: django templates for-loop label formset


    【解决方案1】:

    您可以使用自定义模板标签来做到这一点。示例代码如下:

    将以下内容添加到 /{app_name}/templatetags/app_tags.py

    from django import template
    register = template.Library()
    
    @register.filter
    def month(value, counter):
        try:
            month = value[counter]
        except IndexError:
            month = ""
        return month
    

    在您的模板中添加以下内容

    {% load app_tags %}
    
    ............
    ............
    
    {% for form in formset %}
        {{form.id}}
        <div class="field">
            {{ form.Value.errors }}
            <label for="id_Value">{{ months|counter:forloop.counter }}</label>
            {{ form.Value }}
        </div>
    {% endfor %}
    
    ............
    ............
    

    View this link,有人也尝试过不同的方法来做到这一点;虽然他们都没有工作。 ;)

    【讨论】:

    • 感谢您的帮助...您的代码中有一个小错误,在模板中应该是&lt;label for="id_Value"&gt;{{ months|month:forloop.counter0 }}&lt;/label&gt;
    【解决方案2】:

    在 django 模板中没有现成的过滤器/标签。 您可以尝试编写自定义过滤器/标签。参考Custom template tags and filters

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-09
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2012-01-24
      • 2012-03-28
      • 2015-05-20
      • 2022-01-25
      相关资源
      最近更新 更多