Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Displaying subdirectory name in the url in Yii2 for static pages

Iam creating static pages for a client using Yii2. I am using yii2 because the client has some other requirements to scale up the web later. I use Yii2 Basic app. The yii2 basic has default pages like about, contact etc. The url for those pages after enabling pretty url is

 www.example.com/about

etc

Now i need to create pages

"xyz.php"

under a sub directory like

"abc"

. So i need my url to be www.example.com/abc/xyz

How do i achieve this? to be informed iam a learner, I followed url rules, helpers but did not find a strong solution.

like image 739
Nuthan Raghunath Avatar asked Nov 09 '22 03:11

Nuthan Raghunath


1 Answers

create a controller like StaticController.php and use the yii\web\ViewAction http://www.yiiframework.com/doc-2.0/yii-web-viewaction.html

As an example:

namespace app\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\AccessControl;

/**
 * StaticController is only for displaying static pages.
 */
class StaticController extends Controller
{
    public $defaultAction = 'page';

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['page'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'page'=>array(
                'class'=>'yii\web\ViewAction',
                'viewPrefix'=>null, // or set a specific directory e.g. 'static-pages' if you want to store the static pages in a subdirectory
            ),
        ];
    }
}

And add this Rule to your UrlManager (where static is your controller name)

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '<controller:static>/<view:.*>' => '<controller>',
        ...
    ]
]

Now you can store your static pages in the directory /view/static/

e.g. index.php, test.php or even in subdirectories /sub/test2.php

The urls would be like /static (or /static/index), /static/test1, /static/sub/test2

The 1st pathname is of course the controller name, but you can also change the url rule to something else or rename the controller.

like image 83
BHoft Avatar answered Dec 25 '22 09:12

BHoft