Symfony2 如何在路由正则表达式中允许带破折号的 slug? [英] Symfony2 how to allow slug with dashes in routes regex?

查看:28
本文介绍了Symfony2 如何在路由正则表达式中允许带破折号的 slug?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的路线(slug 包含破折号!):

My route (slug contains dashes!):

region:
  pattern: /regione/{slug}-{id}
  defaults: { _controller: SWAItaliaInCifreBundle:Default:region }

在 Twig 模板中:

In Twig template:

{% for r in regions %}
    <a href='{{ path('region', { 'slug':r.slug, 'id':r.id }) }}'>{{ r.name }}</a>
{% endfor %}

我收到关于正则表达式匹配的错误.问题:为什么 Symfony2 不允许在 url 中使用破折号?我如何指定我的路线包含破折号(而且完全没问题)?

I'm getting an error about regular expression matching. Question: why Symfony2 does not permit dashes in url? How can i specify that my route contains dashes (and it's perfectly fine)?

模板渲染过程中抛出异常(路由区域"的参数slug"必须匹配[^/-]+?"(给出了valle-d-aosta-vallee-d-aoste").

An exception has been thrown during the rendering of a template ("Parameter "slug" for route "region" must match "[^/-]+?" ("valle-d-aosta-vallee-d-aoste" given).")

推荐答案

默认情况下禁止使用斜杠.您可以通过更改默认要求来启用它们.在你的情况下,给出对 id 的要求也很好,因为它用破折号分隔.

Slashes are by default forbidden. You can enable them by changing the default requirements. In your case it'd be also good to give requirements for the id as it's separated with dash.

见下面的例子.

region:
    pattern: /regione/{slug}-{id}
    defaults:
        _controller: SWAItaliaInCifreBundle:Default:region
    requirements:
        slug: "[a-zA-Z1-9-_/]+"
        id: "d+"

这篇关于Symfony2 如何在路由正则表达式中允许带破折号的 slug?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆