好吧,这是我的情况。我有一组通用对象,我正在 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>
这是一个老问题,但是 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 %}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)