Jelmer Keij
Jelmer Keij

Reputation: 1606

Yii 2: Can I access a variable in a view that's rendered by another view?

In Yii 2, following the MVC pattern the controller passes certain variables to the view. However, sometimes the view renders another view in itself.

For example in the default generated CRUD views, both create.php and update.php render the _form view:

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

Is it possible for me to use a variable passed by the controller to create.php in _form?

Say the controller renders it like this:

return $this->render( 'create', [
    'model' => $model,
    'myVar' => $myValue,
] );

Now I can access $myVar in create.php but I can't in _form (which is rendered by create.php. Is there anyway I can access this? Or do I need to explicitly pass it to form like this (in create.php):

return $this->render( '_form', [
    'model' => $model,
    'myVar' => $myValue,
] );

Upvotes: 4

Views: 4125

Answers (3)

JQL
JQL

Reputation: 1

I used this to pass a variable from one view to another:

View1:

<?= $this->render('@app/views/layouts/_view2.php', ['hideCarousel' => TRUE]) ?>

View2:

<?php if (!isset($hideCarousel)): ?>
    ...
<?php endif; ?>

Upvotes: -1

arogachev
arogachev

Reputation: 33538

You need to continuously pass it to view where you want to access it.

Example:

In controller:

return $this->render('view1', ['var' => $value]);

In view1:

<?= $this->render('view2', ['var' => $var]) ?>

Then you can access variable var as $var in view view2.

Upvotes: 2

Blizz
Blizz

Reputation: 8400

The render-function uses extract() to convert your parameters into regular variables in the local function context, which is where the include of the file is done. That is how you "receive" those values in your view.

This means that if you call render (or any of the other variants) again within that view, it will create a new local context and the local variables from "above" won't be there. Which is why it is required that you pass along the variables to every call, as you already figured out yourself.

Upvotes: 3

Related Questions