将参数传递给规则中的路由

将参数传递给规则中的路由

本文介绍了yii2 路由 - 将参数传递给规则中的路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户访问域/页面时,我需要将它们路由到controller/action/100.我不想通过URL传递任何参数,而是想将其添加到url规则中.

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
    ],
],

第一条规则运行良好.

我可以在 url 规则中传递路由的参数吗?

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

推荐答案

您需要使用 defaults 并明确声明规则:

You need to use defaults and declare the rule explicitly:

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

添加 'mode' =>\yii\web\UrlRule::PARSING_ONLY 如果您想在使用 UrlManager 创建 URL 时阻止转换(例如 Url::to() 使用 UrlManager 和它的规则和工作方向相反,即 Url::to(['cms/page', 'id' => 10]) 将生成一个链接 about)

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.

这篇关于yii2 路由 - 将参数传递给规则中的路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 06:24