> Symfony中文手册 > 如何在路由参数中允许“/”字符

如何在路由参数中允许“/”字符

有时,你需要一个含有/斜杠的参数来组成 URL 。例如,经典的 /hello/{username} 路径。默认情况下,/hello/Fabien 将匹配该条路由,但/hello/Fabien/Kris就行了。这是因为 Symfony 使用 / 这个字符作为路由各部分之间的分隔符。

本指南主要涉及如何修改路由,以使/hello/Fabien/Kris也能匹配/hello/{username}路由,此时的{username} 就等于Fabien/Kris

配置路由 ¶

默认情况下,symfony的路由组件要求参数应匹配下面的正则表达式[^/]+。这意味着所有的字符除了/都被允许。

如果你一定要让/成为参数的一部分,那么你就要指定一个更宽松的路径表达式:

1
2
3
4
5
6
7
8
9
10
11
12
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
 
class DemoController
{
    /**
     * @Route("/hello/{username}", name="_hello", requirements={"username"=".+"})
     */
    public function helloAction($username)
    {
        // ...
    }
}
1
2
3
4
5
_hello:
    path:     /hello/{username}
    defaults: { _controller: AppBundle:Demo:hello }
    requirements:
        username: .+
1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8" ?>
 
<routes xmlns="Http://symfony.com/schema/routing"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
 
    <route id="_hello" path="/hello/{username}">
        <default key="_controller">AppBundle:Demo:hello</default>
        <requirement key="username">.+</requirement>
    </route>
</routes>
1
2
3
4
5
6
7
8
9
10
11
use Symfony\Component\Routing\RouteCollection;
use Symfony\Component\Routing\Route;
 
$collection = new RouteCollection();
$collection->add('_hello', new Route('/hello/{username}', array(
    '_controller' => 'AppBundle:Demo:hello',
), array(
    'username' => '.+',
)));
 
return $collection;

就是这样!现在,{ username }参数可以包含/字符了。