2

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

2
  • Can you give us a use case to prepare example Commented Apr 20, 2013 at 9:17
  • Until then, maybe Akrabats Layout Examples will help you out. Commented Apr 20, 2013 at 10:06

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.