【问题标题】:Django url template tag with variable带有变量的 Django url 模板标签
【发布时间】:2014-04-16 16:06:49
【问题描述】:

在我的 urls.py 中我有一些类似的东西

 # Dont use repeating patterns when only the end changes.
 url(r'^products/', include(patterns('foo.apps.bar.views',
    url(r'^$', 'product_family', name='products'),
    url(r'^(?P<page>[\w-]+)$', 'product_single'),
    ...
 ))),

相当于:

www.demo.com/products/ - 带您到我们查看所有产品的页面 www.demo.com/products/alpha - 带您进入 alpha 产品页面 - 如果 alpha 不存在,它会重定向到产品页面

我可以通过 urls.py 中指定的“名称”链接到这些页面

<a href="{% url 'products' %}">Products</a>

我怎样才能做到这一点,但提供一个变量将我带到 product_single?

<a href="{% url 'products/{{ products.slug }}' %}">Products</a>

我知道我可以写出不带 url 标签的链接,但很好奇是否有语法可以像上面的 a href 那样使用它?

【问题讨论】:

    标签: django


    【解决方案1】:

    为您的单个产品网址命名。

    url(
        r'^products/',
        include(
            patterns('foo.apps.bar.views',
                url(r'^$', 'product_family', name='products'),
                url(r'^(?P<page>[\w-]+)$', name='product_single'),
            )
        )
    ),
    

    将slug 传递给新命名的url。

    <a href="{% url 'product_single' products.slug %}">Products</a>
    {# OR #}
    <a href="{% url 'product_single' page=products.slug %}">Products</a>
    

    【讨论】:

    • 噢!我知道它会是这样的,看起来也很干净。非常感谢先生!将在几分钟内接受。
    • 总是乐于提供帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2019-07-31
    • 2020-05-02
    • 2015-03-16
    • 2013-05-12
    • 1970-01-01
    相关资源
    最近更新 更多