Eduardo Eduardo - 1 year ago 472
PHP Question

Yii. Render can work as renderPartial too?

In the past, with Yii 1, I use to load partial views with "renderPartial", if you did not use renderPartial, it loaded the "partial view" with layout. Now in Yii2, method renderPartial has been moved to the controller, BUT you also can do:

<?= $this->render('_form', [
'model' => $model,
]) ?>

Inside another view, and it works same way as renderPartial, what kind of sorcery is this? :D. I guess in some level Yii2 checks if it is being loaded inside another view and uses renderPartial but I have not been able to find it. Anyone has found this?

I came to this question, because I was reviewing Pjax, playing with it and I saw a couple examples where the controller used return $this->render but Pjax still worked, as far as I know Pjax stops working if
tag or error has been found on the response, am I right?

Answer Source

All the controller and view render() methods are essentially using the same method, part of the view model. It's a key concept in DRY (don't repeat yourself) The view model has this method;

public function render($view, $params = [], $context = null)
        $viewFile = $this->findViewFile($view, $context);
        return $this->renderFile($viewFile, $params, $context);

All it does is render the view file specified by $view.

Now in the controller, you have two methods; render() and renderPartial(). The difference is just that in one a layout is applied, and in the other it isn't. The code looks like this;

public function render($view, $params = [])
    $content = $this->getView()->render($view, $params, $this);
    return $this->renderContent($content);

The first line in the method does two things. Firstly it gets the view object, then, by chaining, it uses the render() method of that view object to generate the html from that view.

The second line then passes that content on to the renderContent() method of the controller, which applies any layout to the content.

The code for renderPartial() is this;

public function renderPartial($view, $params = [])
    return $this->getView()->render($view, $params, $this);

As you can see, it's exactly the same as the render() method of the controller, except that it doesn't pass anything to the renderContent() method of the controller, it just outputs it.

As for the pjax part of your question, I'm guessing that as long as your pjax doesn't generate any substantial errors, it will work whether you are using $controller->render(), $controller->renderPartial() or $view->render().

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download