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

后端 未结 4 586
夕颜
夕颜 2021-02-12 16:58

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

4条回答
  •  深忆病人
    2021-02-12 17:17

    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. This code has been tested with Django 1.4.

    I followed the instructions about Custom Filters. My filter code looks as such.

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

提交回复
热议问题