Reputation: 4862
I finished reading (url in Built-in template tags and filters).
When are URL tags useful?
Upvotes: 0
Views: 95
Reputation: 6318
The URL tag is used when you want to link to a view. You do NOT want to have the view URL hard-coded into your template - so you use the URL tag. That way if you change the URL to your view, you do not need to comb through every single template and make sure that your hard-coded URL to that view is changed as well.
You can also pass variables for the view that you are linking in the template tag as outlined below.
Let's say you have a view called section, like so:
def section(request):
code....
And in the section
template, you want to pass a parameter to a different view, people
:
def people(request, section_id):
code....
Notice that people
takes a parameter, section_id
. So in your section
template you could use the url tag in a link, passing the section_id
, like so:
<a href="{% url views.people section_id %}">Link to People View - Passing Section_ID </a>
And in the people
template you can link back to the section
view - which does not need any parameters:
<a href="{% url views.section %}">Link to Section View - No parameters needed </a>
Edit: It looks like starting in Django 1.5, the first parameter, the view, must be in quotes like so:
{% url 'views.section' %}
.
Since 1.5 is still in dev, I'm going to leave the above as 1.4 style.
Upvotes: 2