Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django template object type

Alright, here's my situation. I've got an array of generic objects that I'm iterating over in a django template. Those objects have a number of subclasses and I want to figure out in the template which subclass I'm dealing with. Is this possible? Advisable?

The code might look something along the lines of (where the if statements include some imaginary syntax):

<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>
like image 810
prauchfuss Avatar asked Mar 25 '11 02:03

prauchfuss


People also ask

What does {{ name }} this mean in Django templates?

What does {{ name }} this mean in Django Templates? {{ name }} will be the output. It will be displayed as name in HTML. The name will be replaced with values of Python variable.

Does Django use jinja2?

Jinja is officially supported by Django, and even before that there were third-party packages that allowed you to use it. The only real compatibility issue is that you can't use Django's custom template tags in a Jinja template.

Which option does Django templates accept?

DjangoTemplates engines accept the following OPTIONS : 'autoescape' : a boolean that controls whether HTML autoescaping is enabled. It defaults to True . Only set it to False if you're rendering non-HTML templates!


2 Answers

This is an old question, but FWIW you can do this with a template filter.

@register.filter
def classname(obj):
    return obj.__class__.__name__

Then in your template you can do:

{% with beer|classname as modelclass %}
{% if modelclass == "Domestic" %}US of A
{% elif modelclass == "Import" %}Somewhere else
{% endif %}
{% endwith %}
like image 138
imiric Avatar answered Oct 24 '22 12:10

imiric


You'll have to do it via some sort of method. Why not just write a method like display_location() or something on the model itself and have it return the string which gets rendered there? Then you could just put {{ beer.display_location }} in your template.

Or if you want to go really crazy, write a custom template tag that does what you want, but that's much more work.

like image 39
Daniel DiPaolo Avatar answered Oct 24 '22 11:10

Daniel DiPaolo