How to write better template tags in django

django, django-templates

Solution

Evgeny has a good idea with the smart_if template tag. However, if that doesn't work, you will probably find that a custom filter is easier to write for this sort of comparison. Something like:

@register.filter
def is_in(obj, val):
    return val is in obj

and you would use it like this:

{% if user|is_in:group.users %}

Problem

I've seen how I can write template tags that set a context variable based on a template like this ``` {% my_template_tag 'blah' as my_context_variable %} ``` But I'd like to be able to do this: given that both `group` and `user` are set in the context in the view ``` {% is_in_group group user as is_member %} {% if is_member %} #.... do stuff .... {% endif %} ``` or ideally something like this: ``` {% if is_in_group group user %} # .... {% end if %} ``` Obviously the other way round is to just set `is_member` in the view - but this is just an example and would be good to know how to do something like this anyway!

Original source