aserwin
aserwin

Reputation: 1050

Zend Framework 2 layout.phtml

So, as I can write code in the controller to affect the view... What code does the layout.phtml read from? (I am assuming the module.php, but I'd like some feedback)

EDIT: to be clear... in my controller, I can get a variable equal to something and access it in my view. I'd like to discover a similar action inside my layout.

thanks

Upvotes: 2

Views: 2080

Answers (1)

Jurian Sluiman
Jurian Sluiman

Reputation: 13558

You ask various questions in this single post. I will try to address a few of them.

How does a layout work?

In Zend Framework 2 there is the concept of "view models". A view model is an object that has a couple of variables and a template assigned. This template is rendered with the given variables.

Furthermore, you can nest view models. So one view model (the "layout") has a child which is created from your controller. The child is rendered and stored as a variable in the parent view model. The name of this variable is called the "capture to".

What happens, is you have a controller and then a view model is created. This view model is inserted as a child view model in a new model, which is the layout. This child is set with a "capture to" of content. So in the layout, the result of the child view model is inserted in the $content variable.

How do you access layout variables in the controller?

There is a a layout controller plugin which gives you direct access to the layout view model. So you can set variables directly there:

public function indexAction()
{
    $this->layout()->setVariable('foo', 'bar');
}

Then $foo echos bar in your layout.

How do you access layout variables in a view script?

There is a a layout view helper which also gives you direct access to the layout view model. So you can set variables there too:

<?php $this->layout()->foo = 'bar';?>

Then $foo echos bar in your layout.

Upvotes: 10

Related Questions