Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 747
cusejuice Avatar asked Feb 14 '23 02:02

cusejuice


1 Answers

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.

like image 101
alecxe Avatar answered Feb 16 '23 11:02

alecxe