[Answered ]-How to give {% url '' %} to a variable?

2👍

The url tag can be assigned to a variable through using as.

{% url 'my_url' as foobar %}
{{ foobar }}

But that doesn’t make sense in the current place where you’re using it. Just assign the anchor tags inside of the if/else statements

{% if user.is_admin %}
    <a href="{% url 'url_to_admin' %}">admin</a>
{% else %}
    <a href="{% url 'url_to_other' %}">other</a>
{% endif %}

0👍

Not the answer, but you may try this:

<a href='{% if user.is_admin %}{% url 'url_to_admin' %}{% else %}{% url 'url_to_other' %}'>other url </a>

0👍

why don’t you handle it in the views before you render the template, try something like in your view.py
if User.is_admin:
url = 'url_to_admin'
else:
url = 'url_to_other'
render(request, "your_template.html", {'url' : url})

then you can go ahead and call your url in your template like
<a href= "{{ url }}>url</a>"

0👍

views.py

from django.core.urlresolvers import reverse
def my_view(request):
    if request.user.is_admin:
        my_url = reverse('my_admin_view')
    else:
        my_url = reverse('my_other_view')
    return render(request, 'my_template.html', {'my_url': my_url })

Using django.core.urlresolvers.reverse

my_template.html

<a href="{{ my_url }}">This is a link</a>

Leave a comment