【问题标题】:Passing multiple parameters in a hyperlink in yii2 with clean urls, Html::a() doesnt generate clean url在 yii2 的超链接中使用干净的 url 传递多个参数,Html::a() 不会生成干净的 url
【发布时间】:2015-05-28 19:14:24
【问题描述】:

我正在尝试通过中提到的方法生成超链接 http://www.yiiframework.com/doc-2.0/guide-helper-html.html#hyperlinks这样的

 Html::a('<b>Register</b>', 
    ['story/create', array('id' =>39,'usr'=>'11')], 
    ['class' => 'profile-link'])

我想得到像story/create/id/39/usr/11这样的网址

但它生成为

story/create?1%5Bid%5D=39&1%5Busr%5D=1

我已经启用了yii2之类的clean url功能

  'urlManager' => [
        'class' => 'yii\web\UrlManager',
        // Disable index.php
        'showScriptName' => false,
        // Disable r= routes
        'enablePrettyUrl' => true,
        'rules' => array(
                '<controller:\w+>/<id:\d+>' => '<controller>/view',
                '<controller:\w+>/<action:\w+>/<id:\d+>' => '<controller>/<action>',
                '<controller:\w+>/<action:\w+>' => '<controller>/<action>',
        ),
        ], also.

如何做到这一点?

【问题讨论】:

    标签: yii2 clean-urls yii-url-manager


    【解决方案1】:

    使用 generate url 那样使用(查看更多http://www.yiiframework.com/doc-2.0/guide-helper-url.html):

    Html::a('<b>Register</b>', 
            ['story/create', 'id' =>39,'usr'=>'11'], 
            ['class' => 'profile-link'])
    

    在 urlManager 中输入新规则:

    rules' => array(
      ....
      'story/create/<id:\d+>/<usr:\d+>' => 'story/create',
    
            ),
    

    输出网址会是这样的:

    story/create/39/11
    

    在控制器中:

    public function actionCreate($id, $usr)
    

    而Yii2提供了这个参数。

    【讨论】:

    • 它仍然像故事/创建一样生成?1%5Bid%5D=39&1%5Busr%5D=1
    • Html 中设置['story/create', 'id' =&gt;39,'usr'=&gt;'11'], ?
    • 它现在正在像 reg/create/39?usr=1 一样创建,我需要吗?被删除
    • 我试过了,效果很好。看 - yadi.sk/i/neiWnrkufW43Jyadi.sk/i/pSvwF5GSfW49Z 和我的 .htaccess yadi.sk/i/4jsoxNwffW4D9
    • 我不知道它像 create/39?usr=1 ,可能与 Html::a() 生成超链接有关
    【解决方案2】:

    动态创建网址

    Html::a('<b>Register</b>', 
        ['story/create', 'id' =>39,'usr'=>'11'], 
        ['class' => 'profile-link'])
    

    在 urlManager 配置规则中:

    'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                 '<controller:\w+>/<id:\d+>' => '<controller>/view',            
                 '<controller:\w+>/<action:\w+>/<id:\d+>/<usr:\d+>' => '<controller>/<action>', 
            ],
        ],
    

    输出网址会是这样的:

    story/create/39/11
    

    【讨论】:

      【解决方案3】:

      另一个有用的方法:

      在你的 urlManager 规则中写入

      'rules'=>array('/controller/action/<limit>/<offset>'=>'/controller/action/'),
      

      可以在url controller/action/100/20中访问

      【讨论】:

        猜你喜欢
        • 2014-12-18
        • 1970-01-01
        • 2018-11-29
        • 2012-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多