zendframework / zend-expressive-zendviewrenderer

zend-view PhpRenderer integration for Expressive
BSD 3-Clause "New" or "Revised" License
11 stars 12 forks source link

Access view variables in layout #21

Closed djozsef closed 8 years ago

djozsef commented 8 years ago

I have found no standard way to access view variables from within the layout script.

As I see the problem is that the child ViewModels' variables are not merged with the parent's variables when rolling up in the render chain. I am not sure if it is a bad thing since same keys may overwrite one another but I am almost sure that it worked fine with ZF1. As a workaround you could render the content and the layout separately with the same ViewModel using a blank layout, but it is really a workaround not a proper workflow.

I am not familiar with other view renderer options but I think we should find a standard way to make view variables available to all ViewModel parents and children in the full rendering chain.

Opinions? How do you deal with this?

mtymek commented 8 years ago

Technically you can access child variables from layout like this:

$childViewModel = $this->viewModel()->getCurrent()->getChildrenByCaptureTo('content')[0];
echo $childViewModel->someVar;

But I strongly discourage you from doing so :-) Since layout can be rendered by multiple actions (or error handler), you have to make sure that variables you pass are always set. This can easily lead to bugs.

Instead of accessing this variables, try to write a view helper.

djozsef commented 8 years ago

@mtymek Thanks for pointing out that method.

A view helper is a good idea!