【问题标题】:Why to use {%url ....%} with slug?为什么要将 {%url ....%} 与 slug 一起使用?
【发布时间】:2018-04-13 01:31:00
【问题描述】:

我是 Django 新手,正在制作一个简单的博客来提高我的技能。我无法理解将 {% url XXX %} 与 slug 一起使用的目的。更准确地说;

<a href ="{% url 'theview' post.slug%}">

据我所知,上面的 url 标签会将链接映射到名为“theview”的视图函数。并且在 url.py 上还有一个正则表达式过滤器来捕获点击的链接并将其匹配到适当的视图函数。那么为什么我们使用 {%url%} 虽然有一个过滤器来注意链接是否是 slug ?像这样创建链接还不够;

<a href="{{post.slug}}">

【问题讨论】:

    标签: python django django-templates django-views django-urls


    【解决方案1】:

    我们使用url 标签生成具有给定名称和参数以及关键字参数的uri。如果您不想使用,则需要手动编写每个 url。这是一种不好的做法。

    url(r'^blog/post/(?P<slug>[\w-]+)/$', name='post_detail')
    

    如果你有上面的网址,那么(最好的方法)

    # post.slug = 'learn-python'
    <a href="{% url 'post_detail' post.slug %}" > {{ post }}</a>
    # is equivalent to
    # /blog/post/learn-python/
    

    否则我们需要像这样写

    <a href="/blog/post/{{post.slug}}/" > {{ post }}</a>
    

    &lt;a href="{{post.slug}}"&gt; 将不起作用。

    【讨论】:

    • 哦,我终于明白了。谢谢你的朋友。
    猜你喜欢
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多