yii2 routing - pass parameter to route in rules

冷暖自知 提交于 2019-12-10 12:38:06

问题


When a user accesses domain/page, I need to route them to controller/action/100. I don't want to pass any parameter through the URL, but want to add it in url rules.

I added the code below to my config file.

'urlManager' => [
    'rules' => [
        'login' => 'site/login',  // working
        'about' => 'cms/page/10'  // Not Working
        'about' => 'cms/page?id=10'  // Not Working
    ],
],

The first rule is working fine.

Can I pass the parameter for the route in url rules?


回答1:


You need to use defaults and declare the rule explicitly:

'urlManager' => [            
    'rules' => [
        'login' => 'site/login',
        [
            'pattern'  => 'about', 
            'route'    => 'cms/page',
            'defaults' => ['id' => 10],
        ]  
    ],
],

Add 'mode' => \yii\web\UrlRule::PARSING_ONLY to this rule if you want to prevent the transformation when you create a URL with the UrlManager (e.g. Url::to() uses the UrlManager and its rules and works in the opposite direction, that is Url::to(['cms/page', 'id' => 10]) will generate a link about)

Also consider to configure a redirect at your web server instead.



来源:https://stackoverflow.com/questions/36885779/yii2-routing-pass-parameter-to-route-in-rules

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!