4

How can I assign an url to a variable into a template? I've tried:

{% with url_news = url 'news'  %}

and

 {% with url 'news' as url_news %} 

1 Answer 1

12

Use the as option of the url tag

{% url 'news' as the_url %}
{% if the_url %}
<a href="{{ the_url }}">Link to optional stuff</a>
{% endif %}

Note that when you use this syntax, it will fail silently if the url can't be resolved.

Sign up to request clarification or add additional context in comments.

2 Comments

What about defining multiple urls?
@Clayton you can use the url tag multiple times, for example {% url 'first_view' as first_url %}{% url 'second_view' as second_url %}.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.