【问题标题】:Yii2 - UrlManager and params with hypensYii2 - UrlManager 和带连字符的参数
【发布时间】:2018-07-03 04:18:32
【问题描述】:

我有以下网址:

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/

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答。如果我有:base=es&slug=blog/post-slug-slug?我尝试添加斜线,但没有捕捉到它,有什么建议吗?
    • 我想我找到了:[\w_\/-]*
    【解决方案2】:

    您要做的是根据 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'放在slug的,那么它将解析路由SiteController::actionDetail($slug)到请求。

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

    您可以在this answerYii2 definitive guide 中找到有关此主题的更多信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多