Yii2 - UrlManager and params with hypens


Yii2 - UrlManager and params with hypens



I have the following URLs:


http://test.local/index.php?r=site%2Findex&slug=blog-detail
http://test.local/index.php?r=site%2Findex&slug=blog
http://test.local/



I want to get:


http://test.local/blog
http://test.local/blog-detail
http://test.local/



I am sending all requests to SiteController::actionIndex($slug), I am using Basic Application Template.


SiteController::actionIndex($slug)



So far, I have been able to hide index.php and site/index.


index.php


site/index


'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<slugw+>' => 'site/index',
],
]



But it seems w+ does not match strings with -. Also if slug is empty it should show: http://test.local/.


w+


-


http://test.local/




2 Answers
2



w does not match -. You need to use [w-] instead. And + requires at least one char in your case. You should use * instead:


w


-


[w-]


+


*


'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<slug:[w-]*>' => 'site/index',
],
]





thanks for your answer it worked. If I had: base=es&slug=blog/post-slug-slug? I tried to add the slash but it did not catch it, any suggestion?
– Eduardo
Jul 4 at 0:01





I think I found it: [w_/-]*
– Eduardo
Jul 4 at 4:43



What you are trying to make is make specific url based on GET param. With the following example if the user enters url test.local/Some-nice-article then the SiteController::actionIndex($slug) function will get the param.


SiteController::actionIndex($slug)


'urlManager' => [
'pattern' => '<slug>',
'route' =>'site/index',
'ecnodeParams' => false,
//class => anycustomUrlRuleClass,
//defaults =>
]



Or you want another url to specify whether it is detailed view? You can do it this way:


'urlManager' => [
'pattern' => '<slug>-detail',
'route' =>'site/detail',
'ecnodeParams' => false,
//class => anycustomUrlRuleClass,
//defaults =>
]



In this example, if the users puts the string '-detail' at the of the slug, then it will parse the route SiteController::actionDetail($slug) to the request.


SiteController::actionDetail($slug)



Please note that if you did not yet, enable prettyUrls in the config file



You can find a little more about this topic in this answer or in the Yii2 definitive guide






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

api-platform.com Unable to generate an IRI for the item of type

How to set up datasource with Spring for HikariCP?

Display dokan vendor name on Woocommerce single product pages