Yii2: how to show different layouts depending on url route?

767 Views Asked by At

I want to start using AMP (Accelerated Mobile Pages) for Google and article urls like example.com/my-article must also be available as example.com/amp/my-article, but different layout.

Question: How should I structure my Yii2 code to show different layouts and make url route rules for article controller? Some tips I made:

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,
    ]);
}

What to write in config.php?

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

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

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

There are 1 best solutions below

0
On

You could do something like this in before action

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

    return parent::beforeAction($action);
}

And configure URL manager like this

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

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