如何在Yii2中通过斜杠获取URL中的参数?

时间:2017-06-07 14:30:15

标签: php yii2

我想通过斜杠建立带有参数的网址。

对于exapmle,我想要这段代码:

Url::to(['/controller/action',
    'filter' => 'filter,
    'param1' => 'value1',
    'param2' => 'value2' ...]);

生成网址: //path.to.site/controller/action/filter/param1/value1/param2/value2 ...

有没有办法通过defaut urlManager进行此操作?

2 个答案:

答案 0 :(得分:0)

不确定:

<table>
  <tr>
    <td>
      
        <span class="heading">Box1</span>
        <div class="scroll">
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
        </div>
     
    </td>
    <td>
      <span class="heading">Box1</span>
      <div class="scroll">
        Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
    </td>
    <td>
      
       <span class="heading">Box1</span>
         <div class="scroll">Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br> Some TExt<br>
      </div>
      
    </td>
  </tr>
  <tr>
    <td>Box4</td>
    <td>Box5</td>
    <td>Box6</td>
  </tr>
  <tr>
    <td>Box7</td>
    <td>Box8</td>
    <td>Box9</td>
  </tr>
</table>

然后'urlManager' => [ 'rules' => [ '<controller>/<action>/<filter>/param1/<param1>/param2/<param2>' => '<controller>/<action>', ], ], 将返回以下结果:

Url::to

答案 1 :(得分:0)

use Yii;
use yii\web\UrlRuleInterface;

class SearchUrlRule implements UrlRuleInterface
{

    public function parseRequest($manager, $request)
    {
        $pathInfo = $request->getPathInfo();

        if (strpos($pathInfo, 'somepath') !== 0) {
            return false;
        }

        $parameters = explode('/', $pathInfo);

        if ($parameters[1] !== 'f') {
            return false;
        }

        $route = 'controller/action';

        $params = [
            'filter' => 'f'
        ];
        $count = count($parameters);
        $i = 2;
        var_dump($parameters);
        while (($i + 1) < $count) {
            $params[$parameters[$i]] = $parameters[$i + 1];
            $i = $i + 2;
        }

        Yii::trace("Request parsed with URL rule: action/controller", __METHOD__);

        return [$route, $params];
    }

    public function createUrl($manager, $route, $params)
    {
        if ($route !== 'controller/action') {
            return false;
        }

        if ($params['filter'] !== 'f') {
            return false;
        }
        unset($params['filter']);

        //If a parameter is defined and not empty - add it to the URL
        $url = 'somepath/f/';

        foreach ($params as $k => $param) {
            $url .= "$k/" . $param;
        }

        return $url;
    }
}

这是代码,解决了我的问题。在配置中:

        'rules' => [
            ...
            ['class' => 'frontend\components\SearchUrlRule'],
            ...