在 Yii2 的 url 中为静态页面显示子目录名称

Nut*_*ath 5 yii2 yii2-basic-app

我正在使用 Yii2 为客户端创建静态页面。我正在使用 yii2,因为客户端有一些其他要求,以便稍后扩展网络。我使用 Yii2 Basic 应用程序。yii2 basic 有默认页面,如 about、contact 等。启用漂亮 url 后这些页面的 url 是

 www.example.com/about
Run Code Online (Sandbox Code Playgroud)

等等

现在我需要创建页面

“xyz.php”

在子目录下像

“ABC”

. 所以我需要我的网址www.example.com/abc/xyz

我如何实现这一目标?被告知我是一个学习者,我遵循了 url 规则,帮助者但没有找到一个强有力的解决方案。

BHo*_*oft 1

创建一个类似的控制器StaticController.php并使用 yii\web\ViewAction http://www.yiiframework.com/doc-2.0/yii-web-viewaction.html

举个例子:

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
            ),
        ];
    }
}
Run Code Online (Sandbox Code Playgroud)

并将此规则添加到您的 UrlManager (其中 static 是您的控制器名称)

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '<controller:static>/<view:.*>' => '<controller>',
        ...
    ]
]
Run Code Online (Sandbox Code Playgroud)

现在您可以将静态页面存储在目录中/view/static/

例如index.php, test.php or even in subdirectories /sub/test2.php

网址就像/static (or /static/index), /static/test1, /static/sub/test2

第一个路径名当然是控制器名称,但您也可以将 url 规则更改为其他名称或重命名控制器。