Django模板对象类型 [英] Django template object type

查看:155
本文介绍了Django模板对象类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,这是我的情况。我有一个通用对象的数组,我在django模板中迭代。那些对象有一些子类,我想在模板中找出我正在处理的子类。这可能吗?建议吗?



代码可能看起来像(if语句包含一些虚构语法)的一些内容:

 <表> 
< tr>
< th> name< / th>
< th>首页< / th>
< / tr>
{%for fridge%}
< tr>
< td>
{{beer.name}}
< / td>
< td>
{%如果啤酒是国内的实例%}美国的A {%endif%}
{%如果啤酒是导入的实例%}其他地方{%endif%}
< / TD>
< / tr>
{%endfor%}
< / table>


解决方案

这是一个旧问题,但是FWIW可以做这个与模板过滤器。

  @ register.filter 
def classname(obj):
return obj .__ class __.__ name__

然后在你的模板中你可以做:

  {%with beer | classname as modelclass%} 
{%如果modelclass ==国内%} US $ A
{%elif modelclass ==Import%}其他地方
{%endif%}
{%endwith%}


Alright, here's my situation. I've got an array of generic objects that I'm iterating over in a django template. Those objects have a number of subclasses and I want to figure out in the template which subclass I'm dealing with. Is this possible? Advisable?

The code might look something along the lines of (where the if statements include some imaginary syntax):

<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>

解决方案

This is an old question, but FWIW you can do this with a template filter.

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

Then in your template you can do:

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

这篇关于Django模板对象类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆