How to render menu with one active item with DRY?

Figured out another way to do it, elegant enough thanks to this answer : https://stackoverflow.com/a/17614086/34871

Given an url pattern such as:

url(r'^some-url', "myapp.myview", name="my_view_name"),

my_view_name is available to the template through request ( remember you need to use a RequestContext – which is implicit when using render_to_response )

Then menu items may look like :

<li class="{% if request.resolver_match.url_name == "my_view_name" %}active{% endif %}"><a href="https://stackoverflow.com/questions/9793576/{% url"my_view_name" %}">Shortcut1</a></li>
<li class="{% if request.resolver_match.url_name == "my_view_name2" %}active{% endif %}"><a href="https://stackoverflow.com/questions/9793576/{% url"my_view_name2" %}">Shortcut2</a></li>

etc.

This way, the url can change and it still works if url parameters vary, and you don’t need to keep a list of menu items elsewhere.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)