2014-02-16 71 views
1

我有這個代碼,我使用從樹枝根據相同的日期顯示部分。解決在Django模板中設置變量

我想在Django中使用相同的代碼,但我無法在其模板系統中設置變量。做這件事的理智方式是什麼?正確的方法?人們如何解決這個問題?

{% set date = "prout" %} 

{% for article in articles %} 
    {% if article.date != date %} 
    {% if date != "prout" %} 
      </ul> 
     </section> 
    {% endif %} 

    {% set date = article.date %} 

    <section class="row"> 
     <h2>{{ article.date }}</h2> 
     <ul> 
      <li>+ {{ article.titre }}</li> 
    {% else %} 
     <li>+ {{ article.titre }}</li> 
    {% endif %} 
{% endfor %} 
</ul> 
</section> 
+1

你應該做你的邏輯視圖中沒有模板。在django中,你也可以做{%with'prout'as date%} –

+0

我對Django來說很新,我不知道該怎麼做。在視圖還是模型中? –

+0

在視圖中設置的上下文 – vadimchin

回答

0

'設置'變量的概念更接近with標記。引用Built-in template tags and filters django docs

緩存下一個簡單的名稱的複雜變量。當訪問多次「昂貴」的方法(例如,命中數據庫的方法)時,這是有用的 。

例如:

{% with total=business.employees.count %} 
    {{ total }} employee{{ total|pluralize }} 
{% endwith %}