5

I am trying to make the following template snippet work:

<ul>
  {% for name,label in entries.items %}
    <li><a href="{% url name %}">{{ label }}</a></li>
  {% endfor %}
</ul>

As you can see name is a variable that I need to expand into string before passing it to the url built-in tag.

Unfortunately the aforementioned template snippet results in the following exception:

Exception Type: TemplateSyntaxError
Exception Value:    
Caught NoReverseMatch while rendering: Reverse for 'name' with arguments '()' and keyword arguments '{}' not found.

Any ideas or alternative methods on how to achieve this?

2 Answers 2

3

Your code should work for Django >= 1.4 (iirc) - assuming name resolves to a valid url name and this url don't need args or kwargs. For Django 1.3x you have to add {% load url from future %} to your template for this to work. For django < 1.3 you're out of luck (well, you'll have to write a custom tag) - but you should possibly consider porting your code anyway.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the answer I was looking for. It works! Thanks! :) (I am using django 1.3.7)
3

You can pass variable to {% url %} templatetag. If name is valid urlpattern name this snippet should work.

If you need to convert name to a valid urlpattern name, you can do it by using custom filter, like this:

{% url name|my_filter %}

2 Comments

Thanks for the answer. It seems to be a bit redundant the creation of a custom filter that just calls the django url resolver function; this is why I was hoping for a solution within the template.
@niekas: the exemple syntax you posted is for filters, not tags.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.