Spiga

Zend Framework View partial without reseting variables

by Gabi Solomon

Important

Ignore this solution, there is already a solution in ZF implemented in View as Jani Hartikainen pointed out in the comment below.
Its $this->render('...');

Zend Framework has a view helper called partial that you can use to render other views in your view file.
This is very useful for reusing the html code.

The problem i sometimes faced with that partial helper is that it resets all the variables and you need to specify them as an array parameter if you want them to be available in the partial view rendered.

The solution

To overcome this all you need to do is make a new view helper ... i called mine GSD_View_Helper_Render witch extends the Zend_View_Helper_Partial and overwrites the methods that clones the view and resets the variables.

PHP:
  1. class GSD_View_Helper_Render extends Zend_View_Helper_Partial {
  2.  
  3.     public function cloneView()
  4.     {
  5.         $view = clone $this->view;
  6.         // $view->clearVars(); ... this was the line that resets all the variables.
  7.         return $view;
  8.     }
  9. }

Thats it. Hope this is of help to you.
Cheers

Related Posts

  • Was there some reason just doing $this->render(...) was not enough and you needed this?
  • @Jani Hartikainen
    I will have to do a culpa mia :( ... you are right .... i have overlooked the existing method from View
  • We even document that unless you're passing variables to your partial explicitly, you're taking a big performance hit by using partials, and it's better to use render(). :-)
  • @Matthew
    I guess i will have to do a culpa mia again, and start reading the manual again with more attention
  • ari
    render seems to be 100% more preferable than partial for my projects. its a shame i wasted hours and complicated my project needlessly by using partials. the only mention i've seen for a render function in the reference documentation is for the action helper. zend should mention it in the view helpers section of the reference
  • @Ari
    I agrre i think they should write about using render in the manual, and specify the difference between render & partials and how and when to use them
  • bogdanghervan
    The "Important" note is so small that I managed to see it right just after I figured out how to do it myself, which is to send all the view's vars as a model to the partial.

    <?php echo $this->partial('partials/some_partial.phtml', [NULL, ]$this->getVars()); ?>

    You have to start with the idea that some mechanisms should already be available since the issue seems pretty common.
blog comments powered by Disqus