Search code examples
zend-framework2partial-viewsview-helpers

ZF2 Nesting Views in View Helper


I'm attempting to create a ZF2 view helper which outputs a blog post of varying display formats. The post is made up of a header, body and footer.

I've attempted to create the view helper using the nesting example in the ZF2 docs.

// post helper

public function __invoke( PostInterface $post, $is_single = true ){
$view_model = new ViewModel(); 

$view_model->setTemplate( 'editorial/partials/complete' );
$view_model->setVariable( 'object', $post );
$view_model->setVariable( 'is_single', $is_single );

$body_model = new ViewModel();
$body_model->setTemplate( 'editorial/partials/xx_display_format_partial_xx' );
$body_model->setVariable( 'object', $post );    
$view_model->addChild( $body_model, 'body' );
... repeat for header and footer

return $this->getView()->render( $view_model );
}

// editorial/partials/complete.phtml

echo $this->header;
echo $this->body;
echo $this->footer;

I receive no errors when echoing the view helper. The problem is, there's no output either.

Is what I'm trying to do even possible? If so, what am I doing wrong?


Solution

  • Try this solution https://stackoverflow.com/a/15193978/981820

    It says that that PphRenderer actually does not render the child views. The tutorial shows how it works from the action point of view, and it works because in that case the view is rendered by Zend\View\View::render()

    So, the solution to your problem is to render your nested views the same way it's done there.

    UPDATED

    Or you can do it even simpler. Just render your views separately and attach each output to your main view as a variable. See an example:

    $view = new ViewModel();
    $body = new ViewModel();
    $header = new ViewModel();
    $footer = new ViewModel();
    
    //... some setup
    
    $view->setVariable('body', $this->getView()->render($body));
    $view->setVariable('header', $this->getView()->render($header));
    $view->setVariable('footer', $this->getView()->render($footer));
    
    
    return $this->getView()->render($view);
    

    It should be the same outcome and more optimized in terms of your task. The reason why the code from the Zend\View\View::render() is more complex than this one it's because it oversees all the possible cases, but you don't have to do the same for your task.