URL routing rules in Yii2
Coming from a Laravel and Rails background, I find it quite difficult to understand how Yii2 rules work.
I am looking for the following URL patterns:
- /articles/
- / articles / view /
- / articles / 1 / my ugly-articles
ArticlesController
is defined as follows:
<?php
namespace app\controllers;
class ArticlesController extends \yii\web\Controller
{
public function actionIndex()
{
return $this->render('index');
}
public function actionView()
{
return $this->render('index');
}
}
So far I have tried:
'urlManager' => [
'showScriptName' => false,
'enablePrettyUrl' => true,
'rules' =>
[
'articles/view' => 'article/view'
],
],
What I'm most interested in is redirecting my template to the controller @ method.
+3
source to share
1 answer
You can use <id>
param:
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
'rules' => [
'<controller:\w+>/<action:\w+>' => '<controller>/<action>',
'<controller:\w+>/<id:\d+>/<slug:\w+>' => '<controller>/view',
],
],
And your goods controller:
<?php
namespace app\controllers;
class ArticlesController extends \yii\web\Controller
{
public function actionView()
{
$id = (int) Yii::$app->request->get('id');
return $this->render('index');
}
}
+6
source to share