[Django]-Django โ€“ How to use custom template tag with 'if' and 'else' checks?

52๐Ÿ‘

โœ…

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 %}
๐Ÿ‘คPriyank Patel

Leave a comment