代码之家  ›  专栏  ›  技术社区  ›  Eduardo

yii2-urlmanager和params与hypens

  •  0
  • Eduardo  · 技术社区  · 7 年前

    我有以下网址:

    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.php site/index 是的。

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

    但看起来 \w+ 字符串与不匹配 - 是的。如果弹头是空的,它应该显示: http://test.local/ 是的。

    2 回复  |  直到 7 年前
        1
  •  1
  •   rob006    7 年前

    \w 不匹配 - 是的。你需要使用 [\w\-] 相反。以及 + 在您的案例中至少需要一个字符。你应该用 * 相反:

    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
           '<slug:[\w\-]*>' => 'site/index',
        ],
    ]
    
        2
  •  1
  •   Tamas Kelemen    7 年前

    您要做的是基于get param创建特定的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) 按照要求。

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

    你可以在 this answer 或者在 Yii2 definitive guide

    推荐文章