1

I have this requirement in django template:

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

and now, I want let it more simple, I want let url to a variable `xx', like this:

if user.is_admin:
    myurl = {% url 'url_to_admin' %}
else:
    myurl = {% url 'url_to_other' %}

<a href={{myurl}} > url </a>

But I don't know how to write in django's template?

2

4 Answers 4

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
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>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.