dangerChihuahua007
dangerChihuahua007

Reputation: 20895

How do I curtail my url tags in Django templates?

I have many a long list of URLs in a navigation bar in a Django template.

<a href="{% url animals.views.bear %}">The Big Bad Bear</a>
<a href="{% url animals.views.cat %}">The Cat</a>
<a href="{% url animals.views.dog %}">The Dog</a>
...

How do I avoid repeating animals.views. before each URL template tag?

Upvotes: 0

Views: 69

Answers (2)

Yuval Adam
Yuval Adam

Reputation: 165242

You can use the with tag:

{% with av=animals.views %}
<a href="{% url av.bear %}">The Big Bad Bear</a>
<a href="{% url av.cat %}">The Cat</a>
<a href="{% url av.dog %}">The Dog</a>
{% endwith %}

The proper way, however, would be to set the proper names on your URL confs, just as Alex described.

Upvotes: 3

Alex Emelin
Alex Emelin

Reputation: 834

you can name your urls : documentation

in your urls.py:

import views
urlpatterns = patterns('',
    url(r'^bear/$', views.bear, name="bear"),
    url(r'^cat/$', views.cat, name="cat"),
    url(r'^dog/$', views.dog, name="dog"),
    ...
)

then your template code will look like:

<a href="{% url bear %}">The Big Bad Bear</a>
<a href="{% url cat %}">The Cat</a>
<a href="{% url dog %}">The Dog</a>
...

but remember, that it is convinient to name your urls using app prefix, in your case animal

Upvotes: 2

Related Questions