【发布时间】:2013-01-05 05:11:37
【问题描述】:
我读完了 (url in Built-in template tags and filters)。
URL 标签什么时候有用?
【问题讨论】:
标签: python django django-templates
我读完了 (url in Built-in template tags and filters)。
URL 标签什么时候有用?
【问题讨论】:
标签: python django django-templates
当您想要链接到视图时使用 URL 标记。您不希望将视图 URL 硬编码到模板中 - 因此您使用 URL 标记。这样,如果您更改视图的 URL,则无需梳理每个模板并确保该视图的硬编码 URL 也已更改。
您还可以为您在模板标签中链接的视图传递变量,如下所述。
假设您有一个名为 section 的视图,如下所示:
def section(request):
code....
而在section 模板中,您想将参数传递给不同的视图people:
def people(request, section_id):
code....
注意people 带有一个参数section_id。因此,在您的section 模板中,您可以在链接中使用 url 标签,传递section_id,如下所示:
<a href="{% url views.people section_id %}">Link to People View - Passing Section_ID </a>
在people 模板中,您可以链接回section 视图——不需要任何参数:
<a href="{% url views.section %}">Link to Section View - No parameters needed </a>
编辑:看起来从 Django 1.5 开始,第一个参数,视图,必须像这样用引号引起来:
{% url 'views.section' %}。
由于 1.5 仍处于开发阶段,我将保留上述 1.4 样式。
【讨论】: