如何在Django模板中获取对象的类? [英] How do I get the class of a object within a Django template?

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

问题描述

如果我有一个需要类似布局的对象列表,但需要根据对象的类设置一些属性,那么我如何在 class 和其他 xx <时获取类名/ strong>值在模板内不可用。

If I have a list of objects that require similar layouts but need some attribute set based on the class of object how can I go about getting the class name while class and other xx values are not available within templates.


{% for obj in objects %}
 <div class={{obj.__class__.__name__}}
   ..
 </div>
{% endfor }}

这里可能缺少一种替代方法。

There is probably an alternative approach i'm missing here..

推荐答案

有点肮脏的解决方案

如果对象是属于模型的QuerySet,则可以向模型添加自定义方法。

If objects is a QuerySet that belong to a model, you can add a custom method to your model.

 class mymodel(models.Model):
     foo = models........


 def get_cname(self):
    class_name = ....
    return class_name 

然后在您的模板中尝试:

then in your template you can try:

{% for obj in objects %}
   <div class="{{obj.get_cname}}">
     ..
  </div>
{% endfor }}

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

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