Brett
Brett

Reputation: 20059

Yii2 stripping ending slash in Url::to() route when using params

I'm using Yii2 and have been using the Url::to method without any issue. Now I just tried it with params for the first time and it strips the ending slash from my route.

So normally, say I would do this:

Url::to('/my/route/', true);
// http://www.example.com/my/route/

But if I want to pass params, such as:

Url::to('['/my/route/', 'id' => 123, 'name' => 'larry']', true);
// http://www.example.com/my/route?id=123&name=larry

Is there any way to stop it doing this, if not, do I have any other options to get what I want?

My UrlManager rule:

'rules' => [
    [
        'pattern' => 'foo/<name:[0-9a-zA-Z\-]+>.<some_id:\d+>',
        'route' => 'foo/index',
        'suffix' => '/',
    ],
    //.........
],

Upvotes: 0

Views: 3207

Answers (1)

arogachev
arogachev

Reputation: 33548

1) You can achieve that by adding suffix to corresponding url rule containing that route:

'components' => [
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'rules' => [
            [
                'pattern' => 'my/route',
                'route' => 'my/route',
                'suffix' => '/',
            ],
        ],
    ],
],

2) Globally it's available through urlManager property with the same name suffix.

'components' => [
    'urlManager' => [
        'enablePrettyUrl' => true,
        'showScriptName' => false,
        'suffix' => '/',
    ],
],

3) Alternative way of setting through component:

Yii::$app->urlManager->suffix = '/';

This one works for specific routes too, just add this line before calling Url::to();

Upvotes: 2

Related Questions