Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IsInstance in Django template?

Is there a way to do isinstance/issubclass in a Django template? I realise I can write my own templatetag, but I'm surprised this isn't possibly which makes me think I'm either doing something wrong or missing something obvious.

I wish to display two different segments of markup, depending on which type of item I'm displaying whilst iterative over my collection. Thanks!

like image 365
Ludo Avatar asked Aug 22 '11 14:08

Ludo


People also ask

What are Django template tags?

Django Code The template tags are a way of telling Django that here comes something else than plain HTML. The template tags allows us to to do some programming on the server before sending HTML to the client.

What is engine in Django?

Django's template engine provides a powerful mini-language for defining the user-facing layer of your application, encouraging a clean separation of application and presentation logic. Templates can be maintained by anyone with an understanding of HTML; no knowledge of Python is required.


1 Answers

I think a simple template filter here fits the best. It is really quick to implement and easy to call. Something like this:

in templatetags/my_filters.py:

from django import template
from django.utils.importlib import import_module

register = template.Library()

@register.filter
def isinst(value, class_str):
    split = class_str.split('.')
    return isinstance(value, getattr(import_module('.'.join(split[:-1])), split[-1]))

in your template:

{% load my_filters %}

...

{% if myvar|isinst:"mymodule.MyClass" %}
...do your stuff
{% endif %}

Although the above is a sample code (not tested), I believe it should work. For more information on custom template filters please see the django documentation

EDIT: Edited the answer to show that the filter argument is actually a string and not a python Class

like image 154
ppetrid Avatar answered Sep 29 '22 15:09

ppetrid