简体   繁体   English

如何在Django模板中获取对象的类?

[英]How do I get the class of a object within a Django template?

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. 如果我有一个需要类似布局但需要根据对象类设置一些属性的对象列表,我怎样才能获取类名,而和其他xx值在模板中不可用。

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

There is probably an alternative approach i'm missing here.. 可能有一种替代方法,我在这里失踪..

You can also write a custom filter. 您还可以编写自定义过滤器。 My use case was to check whether or not an html element in a Django form was a checkbox. 我的用例是检查Django表单中的html元素是否是一个复选框。 This code has been tested with Django 1.4. 此代码已经过Django 1.4测试。

I followed the instructions about Custom Filters . 我按照自定义过滤器的说明进行操作 My filter code looks as such. 我的过滤器代码看起来如此。

In myapp/templatetags/class_tag.py : myapp/templatetags/class_tag.py

from django import template
register = template.Library()
@register.filter(name='get_class')
def get_class(value):
  return value.__class__.__name__

In your template file: 在您的模板文件中:

{% load class_tag %}

{% if Object|get_class == 'AClassName' %}
 do something
{% endif %}


{{ Object|get_class }}

A little dirty solution 有点脏的解决方案

If objects is a QuerySet that belong to a model, you can add a custom method to your model. 如果对象是属于模型的QuerySet,则可以向模型添加自定义方法。

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

a bit simpler; 有点简单; assuming your layout is a list of a single model: 假设您的布局是单个模型的列表:

class ObjectListView(ListView):
    model = Person
    template_name = 'object_list.html'

    def model_name(self):
        return self.model._meta.verbose_name

Then in object_list.html : 然后在object_list.html

{% for obj in object_list %}
    <div class="{{view.model_name}}">...</div>
{% endfor }}

David's suggestion of a custom filter is great if you need this for several classes. 如果您需要多个类,David建议使用自定义过滤器。

The Django docs neglect to mention that the dev server won't detect new templatetags automatically, however, so until I restarted it by hand I was stuck with a TemplateSyntaxError class_tag is not a registered tag library . Django文档忽略了提到dev服务器不会自动检测新的模板TemplateSyntaxError class_tag is not a registered tag library ,但是,直到我手动重新启动它,我才遇到TemplateSyntaxError class_tag is not a registered tag library

.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM