cusejuice
cusejuice

Reputation: 10671

Django URL names use in Templates

Right now in my templates I hardcore the links in my navigation like the following:

`base.html`

<a href="/about">About</a>
<a href="/contact">Contact</a>
<!-- etc -->

In my urls.py

urlpatterns = patterns('',
    url(r'^about/$', TemplateView.as_view(template_name='pages/about.html'), name='about'),
    url(r'^contact/$', TemplateView.as_view(template_name='pages/contact.html'), name='contact'),
 )

Is there a way that in my base.html file reference the urlpatterns from urls.py so that anytime I change those, it reflects everywhere across my pages and templates?? Something like

<!-- what I would like to do -->
<a href="{{ reference_to_about_page }}">About</a>
<a href="{{ reference_to_contact_page }}">About</a>

Upvotes: 6

Views: 10607

Answers (2)

alecxe
alecxe

Reputation: 473803

This is why url tag was invented:

Returns an absolute path reference (a URL without the domain name) matching a given view function and optional parameters.

If you’re using named URL patterns, you can refer to the name of the pattern in the url tag instead of using the path to the view.

This basically means that you can use url names configured in the urlpatterns in the url tag:

<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>

This gives you more flexibility. Now any time the actual url of about or contact page changes, templates would "catch up" the change automagically.

Upvotes: 11

Alex
Alex

Reputation: 8539

Use Django's url template tag (docs here) with your named url pattern.

Example:

<a href="{% url 'about' %}">About</a>
<a href="{% url 'contact' %}">Contact</a>

Note that the name you put in ' ' will be the name of the particular url pattern in your urls.py. Also, if this is the urls.py file in an app (that is, it gets routed initially from the base urls.py), you'll need to include the namespacing of the app.

Upvotes: 3

Related Questions