django templates:如何将变量扩展为内置标记`url`的字符串参数

fst*_*tab 5 python django templates django-templates

我正在尝试使以下模板片段工作:

<ul>
  {% for name,label in entries.items %}
    <li><a href="{% url name %}">{{ label }}</a></li>
  {% endfor %}
</ul>
Run Code Online (Sandbox Code Playgroud)

正如您所看到name的那样,我需要在将其传递给url内置标记之前将其扩展为字符串.

不幸的是,前面提到的模板片段会导致以下异常:

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

有关如何实现这一目标的任何想法或替代方法?

bru*_*ers 3

您的代码应该适用于 Django >= 1.4 (iirc) - 假设name解析为有效的 url 名称,并且该 url 不需要 args 或 kwargs。对于 Django 1.3x,您必须添加{% load url from future %}到模板中才能使其工作。对于 django < 1.3 你运气不好(好吧,你必须编写一个自定义标签) - 但无论如何你应该考虑移植你的代码。