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

Yii2 - UrlManager and params with hypens

我有以下网址:

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/.

您想要做的是根据 GET 参数进行具体 url。对于以下示例,如果用户输入 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”放在 slug 的开头,那么它将解析路由 SiteController::actionDetail($slug) 到请求。

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

您可以在 or in the Yii2 definitive guide

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

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

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