The Python Oracle

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

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Flying Over Ancient Lands

--

Chapters
00:00 Django - How To Use Custom Template Tag With 'If' And 'Else' Checks?
01:04 Accepted Answer Score 53
01:30 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 %}