Question

This is actually a follow up question to this. When is it better to use a partial view and when is it better to use a view helper?

Was it helpful?

Solution

View helpers

Are normally used if you need to add some repetitive/complex logic within the view. A good example of this are some of the already provided view helpers, such as the Zend\View\Helper\Url.

The Zend\View\Helper\Url is designed to abstract away the repetitive construction of URLs, which otherwise would be considerably messy (and error prone) to do each time you need a link.

echo $this->url('zfcadmin/admin', array('action' => 'index');
/** /admin/home **/ 

The great thing regarding all view helpers is the ability to provided varied data, to a simple API, and have the output be constructed and returned to the view without the view being aware of how the data was generated.

In the case of the URL view helper; There is complex interaction with the Router and it make sense for all of this to be completed in one place.

View Partials

Conversely, view partials are all about "injecting" HTML (or other view data) fragments into other templates. They reduce the need to repetitively write the same HTML structure where only some of the variables are different; Allowing you to create views scripts as reusable 'templates'.

The documentation states

The Partial view helper is used to render a specified template within its own variable scope. The primary use is for reusable template fragments with which you do not need to worry about variable name clashes

I would often use a view partial where there is a small block of HTML that should be reused either as as "widget" or something within a loop.

Note

As there is a clear distinction between what the view partials and view helpers are trying to accomplish, you will often use them in tandem to create your final output. For instance a view partial that you include with $this->partial('/module/foo/bar.phtml', array()); may actually use a view helper within the '/module/foo/bar.phtml (as it is also a view).

Note 2

Just to confuse you even more, when you use $this->partial(); in your view; You are actually using the built in partial view helper Zend/View/Helper/Partial

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top