pra*_*uss 12 django django-templates
好吧,这是我的情况.我有一个通用对象数组,我正在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>
Run Code Online (Sandbox Code Playgroud)
imi*_*ric 26
这是一个老问题,但FWIW你可以用模板过滤器来做到这一点.
@register.filter
def classname(obj):
return obj.__class__.__name__
Run Code Online (Sandbox Code Playgroud)
然后在您的模板中,您可以:
{% with beer|classname as modelclass %}
{% if modelclass == "Domestic" %}US of A
{% elif modelclass == "Import" %}Somewhere else
{% endif %}
{% endwith %}
Run Code Online (Sandbox Code Playgroud)
你必须通过某种方法来做到这一点.为什么不在display_location()模型本身上编写一个类似的东西,并让它返回在那里渲染的字符串?然后你可以放入{{ beer.display_location }}你的模板.
或者,如果你想真的疯了,写一个自定义模板标签,做你想要的,但这是更多的工作.
| 归档时间: |
|
| 查看次数: |
7053 次 |
| 最近记录: |