Yii 2 rendering with layout in places other than controller

Hi All,

I understand that Yii2 has a method to render in other places.

echo \Yii::$app->view->renderFile(’@app/views/site/license.php’);

But by calling that, the layout file will not be applied.

Is there any ways to do so? To render with layout in other places.

Thanks.

I do this at times:


<?php echo \Yii::$app->view->renderFile(Yii::getAlias('@app') . '/views/layouts/dpag.php'); ?>

Seems to work for me.

I am not sure if that will work for my case.

You’re writing to render the layout explicitly, do you write another line to render the body view file?

Hi rockccf,

Check Controller::layout in the API.

https://www.yiiframework.com/doc/api/2.0/yii-base-controller#$layout-detail

Hi everyone,

I’ve figured it out.

Instead of using the view component, use controller instead.


Yii::$app->controller->layout = $layout; //Setting the layout

$html = Yii::$app->controller->render($view, $content);

Thanks.