12

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?

1 Answer 1

28

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.