A free and open-source book on ZF3 for beginners


4.14. View Template Names

When you return data with the ViewModel variable container from your controller's action method, Zend Framework somehow knows the name of the corresponding view template file. For example, for your IndexController's aboutAction() method, ZF3 automatically uses the about.phtml view template.

ZF3 determines the correct view template name by module name, controller name and action name. For example, IndexController::aboutAction() action belonging to Application module will have the application/index/about.phtml view template by default.

If your your controller or action name consists of several words in camel-case (like UserRegistrationController and registrationStep1Action), the corresponding view template will be application/user-registration/registration-step-1.phtml (camel-cased names are converted to lower-case and words are separated by dashes).

4.14.1. Overriding Default View Template Name

The ViewModel can also be used to override the default view template resolving. Actually the ViewModel class is more than just a variable container. Additionally, it allows to specify which view template should be used for page rendering. The summary of methods provided for this purpose is shown in table 4.8.

Table 4.8. Methods of the ViewModel class for setting and retrieving the view template name
Method name Description
setTemplate() Sets the view template name.
getTemplate() Returns the view template name.

To set the view template name, you use the setTemplate() method. The getTemplate() method returns the view template name currently set for the view model.

The following code example shows how you can call the setTemplate() method from your IndexController class' indexAction() method to force ZF3 to use the about.phtml view template file for rendering the Home page, instead of the index.phtml file:

// Index action renders the Home page of your site.
public function indexAction() 
{    
	// Use a different view template for rendering the page.
	$viewModel = new ViewModel();
	$viewModel->setTemplate('application/index/about');
	return $viewModel;
}

In the code above, we created a new instance of the ViewModel class as usual (line 5).

Then we called the setTemplate() method on the view model object (line 6) and passed the name of the view template name as its argument. The view template name is actually a relative path to the about.phtml file, minus file extension.

Finally, we returned the view model object from the action method (line 7).

However, calling the setTemplate() method in every action method is optional. If you don't do that, ZF3 will determine the view template name automatically by concatenating the current module name, controller name and action method name.


Top