5

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

2 Answers 2

9

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.

2

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.

1
  • 1
    For someone that does not know, to include the namespacing, you need to put ":" like: <a href="{% url 'pages:root' %}">; pages is the name of your app and root, the named name of your view (ex: name="root") in urlspatterns.
    – Atem18
    Sep 4, 2022 at 21:55

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.