【问题标题】:Django template object typeDjango 模板对象类型
【发布时间】:2011-07-22 14:50:34
【问题描述】:

好的,这是我的情况。我有一组在 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>

【问题讨论】:

    标签: django django-templates


    【解决方案1】:

    你必须通过某种方法来做到这一点。为什么不在模型本身上写一个像display_location() 这样的方法并让它返回在那里渲染的字符串呢?然后你可以把{{ beer.display_location }}放到你的模板中。

    或者,如果您想真正疯狂,请编写一个自定义模板标签来满足您的需求,但这需要更多的工作。

    【讨论】:

      【解决方案2】:

      这是一个老问题,但 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 %}
      

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-28
      • 2014-11-19
      • 2014-09-07
      • 1970-01-01
      • 1970-01-01
      • 2015-10-06
      • 2014-07-25
      • 1970-01-01
      相关资源
      最近更新 更多