4

I'm using ZF2's View component as standalone for my project like this:

$renderer = new PhpRenderer;
$resolver = new Resolver\AggregateResolver();
$stack = new Resolver\TemplatePathStack(array(
    'script_paths' => array(
        __DIR__ . '/view'
    )
));
$resolver->attach($stack);
$renderer->setResolver($resolver);

$model1 = new ViewModel;
$model1->setTemplate('template1');
$model1->setVariable('key', 'value');

$model2 = new ViewModel;
$model2->setTemplate('template2');

$model1->addChild($model2, 'child');

echo $renderer->render($model1);

It works like charm. The child renders in model1. But the problem is, how can i access model1's variable key in model2?

akond
  • 15,865
  • 4
  • 35
  • 55
cnkt
  • 2,943
  • 5
  • 30
  • 43
  • 1
    I'm too lazy for an actual answer, but this post will help you a lot: http://akrabat.com/zend-framework-2/access-view-variables-in-another-view-model/ he explains how to access child vars in parent, but it works the same way the other way around ;) – Sam Nov 16 '12 at 22:19
  • Thanks but i found it already with google :) But $this->viewModel()->getRoot() returns null for me. – cnkt Nov 16 '12 at 22:22

1 Answers1

1

You can use the Zend\View\Helper\ViewModel to access a common root view model, and possibly traverse the whole view model tree from that.

Just set the root itself:

// right after you instantiated $model1
$modelHelper = $renderer->plugin('view_model');
$modelHelper->setRoot($model1);

And now $this->viewModel()->getRoot() will return $model1 in every view template.

You can peek at how this is dealt with by default in Zend\Mvc\View\Http\ViewManager

Stefano Torresi
  • 686
  • 4
  • 10