0

我想开始为 Google 使用 AMP(加速移动页面),并且文章 url 之类的example.com/my-article也必须以 . 的形式提供example.com/amp/my-article,但布局不同。

问题:我应该如何构建我的 Yii2 代码以显示不同的布局并为文章控制器制定 url 路由规则?我提出的一些建议:

public function beforeAction($action)
{
    if (...) // ??
        $this->layout = 'amp';
    else
        $this->layout = 'main';

    return parent::beforeAction($action);
}

public function actionView($article_slug)
{
    $model = $this->findModel($article_slug);

    if ($this->layout == 'amp')
        $path = 'amp/view';
    else
        $path = 'html/view';

    return $this->render($path, [
        'model' => $model,
    ]);
}

写什么config.php

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [

        // ??
        'amp/<article_slug:[\w\-]+>' => 'article/view',

        '<article_slug:[\w\-]+>' => 'article/view',
    ],
],
4

1 回答 1

1

你可以在行动之前做这样的事情

public function beforeAction($action)
{
    if (\Yii::$app->request->getQueryParam('amp')) {
        $this->layout = 'amp';
    else
        $this->layout = 'main';

    return parent::beforeAction($action);
}

并像这样配置 URL 管理器

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        '<amp>/<article_slug:[\w\-]+>' => 'article/view',

        '<article_slug:[\w\-]+>' => 'article/view',
    ],
],
于 2017-12-26T10:14:22.667 回答