IsInstance in a Django template?

Is there a way to do isinstance / issubclass in a Django template? I understand that I can write my own templatetag, but I am surprised that this is not possible, which makes me think that I am either doing something wrong or missing something obvious.

I want to display two different markup segments, depending on what type of element I am displaying while iterating over my collection. Thanks!

+6
source share
3 answers

If they all inherit from a common base type, but you need to know what type it is, you can simply implement a method on the base that returns the type - then you can call if foo.get_type == 'type1' (or another) in your template.

+5
source

I think that a simple template filter is best suited here. It is very fast to implement and easy to call. Something like that:

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 the template:

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

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

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

+8
source

Something is missing here: the only logic in the template should handle rendering the template. isinstance / issubclass clearly smells like view logic, and should be in the view. If the rendering of the template depends on these functions (which, as I assume), you should implement the logic in the view and just pass the template what it needs to know:

 # in the view: if isinstance(some_obj, SomeClass): do_fancy_template_stuff = True else: do_fancy_template_stuff = False # in the template: {% if do_fancy_template_stuff %} <fancy_template_stuff /> {% endif %} 

Remember: the django template engine was created with non-programmers in mind, such as designers.

0
source

Source: https://habr.com/ru/post/895593/


All Articles