2012-07-04 146 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