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!
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With