Haver
Haver

Reputation: 443

zf2: Nesting View Models Issue

I am trying to create a nested view model with zf2.

I am using standard zf2 skeleton application.

in my IndexController:

public function indexAction()
{
    $view = new ViewModel();
    $view->setTemplate('application/index/index.phtml');

    $aboutView = new ViewModel();
    $aboutView->setTemplate('application/index/about.phtml'); //standard html

    $view->addChild($aboutView, 'about');

    return $view;
}

In my layout.phtml, I added the following code:

HTML code:

echo $this->content

HTML code:

echo $this->about;

The nested view is not showing in the result. When var_dump($this->about), I am getting NULL.

Any Idea what I am doing wrong?

Upvotes: 1

Views: 802

Answers (1)

Andrew
Andrew

Reputation: 12809

You're not using it correctly.

layout.phtml

<?php
/**
 * $view will be assigned to this, with the template index.phtml
 */
echo $this->content 

$aboutView will only be assigned to the ViewModel named $view as a child. To access this you will need to use index.phtml

index.phtml

<?php 
/**
 * This will have the content from about.phtml
 */
var_dump($this->about)

If you want to assign a ViewModel to the actual base ViewModel (which uses layout.phtml) you can access it via layout:

public function testAction()
{
    $aboutView = new ViewModel();
    $aboutView->setTemplate('application/index/about.phtml'); //standard html
    $this->layout()->addChild($aboutView, 'about');

    //$this->layout() will return the ViewModel for the layout :)
    //you can now access $this->about inside your layout.phtml view file.
}

Upvotes: 1

Related Questions