A free and open-source book on ZF3 for beginners

4.13. View Helpers

A view helper is typically a (relatively) simple PHP class whose goal is to render some part of a view. You can invoke view helpers from any view template. With view helpers, you can create reusable widgets (like menus, navigation bars, etc.) for your web pages.

View helpers are analogous to controller plugins: the controller plugins allow to "extend" the functionality of controllers, and view helpers allow to "extend" the functionality of view templates.

ZF3 provides many standard view helpers out of the box. In the table 4.7, some of them are presented with a brief description:

Table 4.7. Standard View Helpers
Standard Plugin Class Description
BasePath Allows to retrieve the base path to the web application, which is the absolute path to APP_DIR.
Url Allows to generate absolute or relative URL addresses from inside view templates.
ServerUrl Retrieves the current request's URL.
Doctype Helper for setting and retrieving the doctype HTML element of the web page.
HeadTitle Helper for setting the title HTML element of the web page.
HtmlList Helper for generating ordered and unordered HTML lists.
ViewModel Helper for storing and retrieving the view model
Layout Retrieves the layout template view.
Partial Allows to render a "partial" view template.
InlineScript Helper for setting and retrieving script elements for inclusion in HTML body section.
Identity View helper to retrieve the authenticated user's identity.
FlashMessenger Allows to retrieve the "flash" messages stored in session.
EscapeHtml Allows to escape a variable outputted to a web page.

To demonstrate the usage of a view helper, below we will show how to set a title for a web page. Typically, it is required to give a different title per each web page. You can do this with the HeadTitle view helper. For example, you can set the title for the About page by adding the following PHP code in the beginning of the about.phtml view template:


In the code above, we call the HeadTitle view helper and pass it the page title string ("About") as the argument. The HeadTitle view helper internally sets the text for the <title> HTML element of your web page. Then, if you open the About page in your web browser, the page title will look like "About - ZF Skeleton Application" (see the figure 4.9 below for an example):

Figure 4.9. Setting page title for the About page Figure 4.9. Setting page title for the About page

We will discuss the view helpers in more details and provide more usage examples in the chapter Page Appearance and Layout.