2013-07-26 39 views
0

我有我的模板以下邏輯:Ifchanged如果不爲null

{% for task in tasks %} 
    {% ifchanged task.shared_task_id %} 
     <tr>{{ task }}</tr> 
    {% endifchanged %} 
{% endfor %} 

不過,我想忽略ifchanged標籤如果shared_task_id是無。例如:

{% ifchanged task.shared_task_id or if task.shared_task_id == None %} 
    <tr>{{ task }}</tr> 
{% endifchanged %} 

有沒有辦法做到這一點?

+0

我對你的問題有些困惑。在你的問題中,如果它的id是'None',你似乎不想打印任務,但是在你自己的回答中,如果它的id是'None',即使沒有改變,你總是希望打印一個任務? – knbk

+0

@knbk謝謝,我更新了我的問題中的代碼來澄清。 – David542

回答

0

試一下這個(與總管Hieu的修復編輯):

{% ifchanged task.shared_task_id %} 
    <tr>{{ task }}</tr> 
{% else %} 
    {% if not task.shared_task_id %} 
     <tr>{{ task }}</tr> 
    {% endif %} 
{% endifchanged %} 

不是真的堅持DRY的原則,但方式不那麼hackish,你現在使用什麼。 Django的模板語言並不適用於高級邏輯,所以我不認爲有更好的解決方案。

如果您需要打印大量的東西,而不是僅僅{{ task }},我想不重複自己豐富和易於更新代碼的疼痛最好的方法是使用一個單獨的模板,並使用{%include <other_template> %}

+0

@ David542 @knbk我認爲這不會奏效。 2串行if語句將允許通過。例如列表[1,無],在第二次迭代中,「任務」將被打印兩次。 –

+0

@Hieu你是對的,更新了我的答案。 – knbk

0

我經過某種hackish的方式在模型現在這樣做:

{% ifchanged task.shared_task_id_or_random %} 

# models.py 
def shared_task_id_or_random(self): 
    return self.shared_task_id or str(random.random()) 

關於如何解決此問題的任何更好的想法?

0

既然你不能在{% ifchange %}andor邏輯,你總是可以使用2如果塊來實現你想要的:

{% for task in tasks %} 
    {% ifchanged task.shared_task_id %} 
     <tr>{{ task }}</tr> 
    {% else %} 
     {% if task.shared_task_id == None %} 
      <tr>{{ task }}</tr> 
     {% endif %} 
    {% endifchanged %} 
{% endfor %}