【问题标题】:When should I use a URL tag in a Django template?什么时候应该在 Django 模板中使用 URL 标签?
【发布时间】:2013-01-05 05:11:37
【问题描述】:

我读完了 (url in Built-in template tags and filters)。

URL 标签什么时候有用?

【问题讨论】:

    标签: python django django-templates


    【解决方案1】:

    当您想要链接到视图时使用 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 样式。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-07-19
    • 2017-12-06
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-08-01
    • 2012-07-25
    相关资源
    最近更新 更多