The Python Oracle

Django - How to use custom template tag with 'if' and 'else' checks?

This video explains
Django - How to use custom template tag with 'if' and 'else' checks?

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: City Beneath the Waves Looping

--

Chapters
00:00 Question
01:26 Accepted answer (Score 49)
02:00 Thank you

--

Full question
https://stackoverflow.com/questions/2255...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #django #djangotemplates

#avk47



ACCEPTED ANSWER

Score 53


You should use Assignment tags :

register = template.Library()

@register.assignment_tag(takes_context=True)
def get_user_perm(context, perm):
    try:
        request = context['request']
        obj = Profile.objects.get(user=request.user)
        obj_perms = obj.permission_tags.all()
        flag = False
        for p in obj_perms:
            if perm.lower() == p.codename.lower():
                flag = True
                return flag
        return flag
    except Exception as e:
        return ""

And after loading tags in templates . use it like :

{% get_user_perm "add_users" as add_users_flag %}
## you can check like this
{% if add_users_flag %} {% else %} {% endif %}