2011-03-25 260 views
9

好的,這是我的情況。我有一個我在django模板中迭代的通用對象數組。這些對象有許多子類,我想在模板中找出我正在處理的子類。這可能嗎?建議?Django模板對象類型

的代碼可能沿東西線(其中if語句包括一些虛構的語法):

<table> 
    <tr> 
     <th>name</th> 
     <th>home</th> 
    </tr> 
    {% for beer in fridge %} 
    <tr> 
     <td> 
     {{ beer.name }} 
     </td> 
     <td> 
      {% if beer is instance of domestic %}US of A{% endif %} 
      {% if beer is instance of import %}Somewhere else{% endif %} 
     </td> 
    </tr> 
    {% endfor %} 
</table> 

回答

21

這是一個老問題,但FWIW你可以用模板過濾器做到這一點。

@register.filter 
def classname(obj): 
    return obj.__class__.__name__ 

然後在你的模板,你可以這樣做:

{% with beer|classname as modelclass %} 
{% if modelclass == "Domestic" %}US of A 
{% elif modelclass == "Import" %}Somewhere else 
{% endif %} 
{% endwith %} 
+0

如何添加自定義過濾器:https://docs.djangoproject.com/en/stable/howto/custom-template-tags/ – clonejo 2017-01-08 00:59:24

8

你必須通過某種方法來做到這一點。爲什麼不直接在模型本身上編寫像display_location()這樣的方法,並讓它返回在那裏呈現的字符串?然後,您可以將{{ beer.display_location }}放在您的模板中。

或者,如果你想變得非常瘋狂,寫一個自定義模板標籤,做你想做的,但這是更多的工作。