2012-07-04 151 views
2

我有以下模板代码,目前我得到循环计数器作为我的formset的标签。我如何获得数组'月'(例如month.counter,其中计数器是循环)的元素作为我的标签?我试过{{month.forloop.counter}},但没有工作如何在模板Django中使用for循环使用数组元素作为标签?

<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> 

回答

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以下

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

+0

感谢您的帮助... jst在你的代码中有一个小错误,在模板中它应该是' ' – nimeshkiranverma