Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering views in other places in Yii2 - no renderPartial?

Tags:

php

yii

yii2

I need to render a partial view inside a custom component file in Yii2 and according to the Yii docs you can access the view instance via something like this:

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

I went ahead and tried:

Yii::$app->view->renderPartial('//my/view/');

...but then got an error that I was trying to access a non-existent method.

I then checked out the view class and noticed it doesn't have a renderPartial and this is a method of the controller class instead.

I see it has a renderFile method and a render method; which of these should I use?

The docs don't state the render method includes the layout like the method of the same name from the controller class, so I'm not sure; as for renderFile I'm not 100% sure if that is suitable either?

Could someone explain which method would produce the same results that renderPartial produces?

like image 580
Brett Avatar asked Aug 16 '15 16:08

Brett


People also ask

How to render a view using $this in Yii?

Remember that $this in a view refers to the view component: In any place, you can get access to the view application component by the expression Yii::$app->view and then call its aforementioned methods to render a view. For example,

How do you render a view in a controller?

Within controllers, you may call the following controller methods to render views: render (): renders a named view and applies a layout to the rendering result. renderPartial (): renders a named view without any layout. renderAjax (): renders a named view without any layout, and injects all registered JS/CSS scripts and files.

How to render a view from a view application component?

In any place, you can get access to the view application component by the expression Yii::$app->view and then call its aforementioned methods to render a view. For example, // displays the view file "@app/views/site/license.php" echo \Yii::$app->view->renderFile ( '@app/views/site/license.php' );


1 Answers

You can call renderPartial from Yii::$app->controller->renderPartial('myview'); Also as you can see from source code of yii\base\Controller renderPartial calls View's render method so you can use Yii::$app->view->render. Basically there is no difference between render and renderFile, because render internally calls renderFile. But when you use render you can pass $view in several formats like path alias, absolute path whithin application or whithin module and relative path. And to renderFile you can pass only absolute file path or path alias.

like image 72
Tony Avatar answered Oct 18 '22 00:10

Tony