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


this question has answer here:

i have made custom template tag permissions using python:

register = template.library()  @register.simple_tag def get_user_perm(request, perm):     try:         obj = profile.objects.get(user=request.user)         obj_perms = obj.permission_tags.all()         flag = false         p in obj_perms:             if perm.lower() == p.codename.lower():                 flag = true                 return flag         return flag     except exception e:         return "" 

then loaded , used in template this:

{% load usr_perm %} {% get_user_perm request "add_users" %} 

which in return prints true. want use check if user has permission or not? how can use template tag if , else conditions? using this:

{% if get_user_perm request "add_users" %}can add user{% else %} permission denied {% endif %} 

is there way can tweak in template tag's code or hint use template tag in template.
n.b: using django's permissions {% if perms.profile.add_user %} due reasons have write own template tag now!
appreciated! thanks

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         p in obj_perms:             if perm.lower() == p.codename.lower():                 flag = true                 return flag         return flag     except exception e:         return "" 

and after loading tags in templates . use :

{% get_user_perm "add_users" add_users_flag %} ## can check {% if add_users_flag %} {% else %} {% endif %} 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -