20

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

4 Answers4

39

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 }}
Community
  • 1
  • 1
davidtingsu
  • 1,090
  • 1
  • 10
  • 17
16

A little dirty solution

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 }}
Andrea Di Persio
  • 3,246
  • 2
  • 24
  • 23
2

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:

{% for obj in object_list %}
    <div class="{{view.model_name}}">...</div>
{% endfor }}
allanberry
  • 7,325
  • 6
  • 42
  • 71
0

David's suggestion of a custom filter is great if you need this for several classes.

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.

.

Chema
  • 705
  • 7
  • 11