2011-10-09 63 views
13

我的路線(塞包含破折號!):Symfony2如何讓路線正則表達式中的破折號?

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

在枝杈模板:

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

我收到一條錯誤正則表達式匹配。 問題:爲什麼Symfony2不允許在URL中破折號?我怎樣才能指定我的路線包含破折號(它完全正常)?

例外,有一個模板 (「參數‘金屬塊’路由‘區域’必須匹配‘[^/- ]的呈現期間被扔?+’ (」山谷-d-奧斯塔-河谷-d-aoste「))

回答

16

斜槓默認是禁止的。您可以通過更改默認要求來啓用它們。在你的情況下,它也是很好的給予ID的要求,因爲它是用短劃線分隔的。

請參閱下面的示例。

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

允許一個尾部斜線在模式的末尾添加一個'/'。例如模式:/ regione/{slug} - {id}/- 然後沒有正則表達式需要 – Michael

+0

需要下面的答案是正確的。這個配置有錯誤的結構和符號 – coviex

+0

@coviex這是一箇舊的答案/符號。更新了我的答案。 –

5

這個正則表達式適合我。 ({ID}要求由邁克爾的建議)

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

爲了使它完成,你可以添加要求:id:\ d + – Michael

1

如果你嘗試這樣它會拋出這樣的錯誤:爲觀看在http://symfony.com/doc/current/cookbook/routing/slash_in_parameter.html 必須使用

An exception has been thrown during the rendering of a template ("Parameter "slug" for route "routing_whatever" must match "[a-zA-Z0-9-_/]+" ("Topics/Virtualization Security" given).") in ... 

毛坯: 「。+」

相關問題