2014-03-25 80 views
1

我開發一個應用程序語句的Python的Django 什麼,我需要做的是一類分配到模板聲明變量,如果在Django模板

{% with 1 as counters %} 
    {% for importance in all_importance %} 

      {% if counters == 1 %} 
       <div class="item active" > 
      {% else %} 
       <div class="item" >   
      {% endif %} 
      {% for image in importance.subtypemodelimage_set.all %} 
       <img src="{{ image.image.url }}" /> 
      {% endfor %} 

     </div> 
     {% counters += 1 %} 
    {% endfor %} 
    {% endwith %} 

但我根據計數器變量值一個div面對這個問題

Invalid block tag: 'counters', expected 'empty' or 'endfor' 

我在哪裏提前犯錯誤,感謝您的幫助

+0

相反你自己開一個櫃檯,Django爲你做這個。 –

+0

@digaph能否請你告訴我該怎麼做,如果你能爲我提供代碼片段,我將不勝感激 –

回答

4

for循環設置了許多循環中可用的變量(完整列表,請Django文檔here):

... 
forloop.first True if this is the first time through the loop 
forloop.last True if this is the last time through the loop 
... 

可以使用forloop.first檢查第一循環迭代:

{% for importance in all_importance %} 

    {% if forloop.first %} 
     <div class="item active" > 
    {% else %} 
     <div class="item" >   
    {% endif %} 

    {% for image in importance.subtypemodelimage_set.all %} 
     <img src="{{ image.image.url }}" /> 
    {% endfor %} 

     </div> 

{% endfor %} 
+0

感謝您的回答,它肯定解決了我在這種情況下的問題,但因爲我是新用戶,我不能投票,我只需要選擇正確的答案,請讓我知道我的代碼有什麼問題意思是如何在Django模板中增加變量 –

+0

@AminBastani你不能自定義模板標籤,因爲我知道,檢查這個例如:http://www.soyoucode.com/2011/set-variable-django-template – ndpu

1

問題是

{% counters += 1 %} 

沒有標籤counters。您正在將變量解釋爲標記。 你不能在django模板中實現那種for循環。

+0

正如你可以在這裏閱讀:https://docs.djangoproject.com/en/dev/ref/templates/ builtins /#與「舊」風格仍然支持 –

+0

@AlexanderMeesters,這與錯誤無關。 – Rohan

+0

OEPS,抱歉,確實沒有,不知道我在想什麼,現在重新閱讀它,你確實是對的。也許我需要更多的咖啡:-)無論如何,我的歉意! –