Yii2-UrlManager和带有连字符的参数

时间:2018-07-03 04:18:33

标签: yii2 yii2-basic-app yii2-urlmanager

我有以下网址:

http://test.local/index.php?r=site%2Findex&slug=blog-detail
http://test.local/index.php?r=site%2Findex&slug=blog
http://test.local/

我想得到:

http://test.local/blog
http://test.local/blog-detail
http://test.local/ 

我正在将所有请求发送到SiteController::actionIndex($slug),我正在使用基本应用程序模板。

到目前为止,我已经能够隐藏index.phpsite/index

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
       '<slug\w+>' => 'site/index',
    ],
]

但是似乎\w+-的字符串不匹配。另外,如果slug为空,则应显示:http://test.local/

2 个答案:

答案 0 :(得分:1)

您要制作的是根据GET参数创建特定的网址。在下面的示例中,如果用户输入URL test.local/Some-nice-article,则SiteController::actionIndex($slug)函数将获取参数。

'urlManager' => [
            'pattern' => '<slug>',
            'route' =>'site/index',
            'ecnodeParams' => false,
            //class => any\custom\UrlRuleClass,
            //defaults => [] 
        ]

还是要另一个URL指定是否为详细视图?您可以这样操作:

  'urlManager' => [
                'pattern' => '<slug>-detail',
                'route' =>'site/detail',
                'ecnodeParams' => false,
                //class => any\custom\UrlRuleClass,
                //defaults => [] 
            ]

在此示例中,如果用户将字符串“ -detail”放在子段的,则它将解析到请求的路由SiteController::actionDetail($slug)

请注意,如果尚未启用,请在配置文件中启用prettyUrls

您可以在this answerYii2 definitive guide

中找到有关此主题的更多信息

答案 1 :(得分:1)

\w-不匹配。您需要改用[\w\-]+在您的情况下至少需要一个字符。您应该改用*

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
       '<slug:[\w\-]*>' => 'site/index',
    ],
]