Changing the View Template / View Script

Today a little topic came up at in which a user wanted to change the view-template for his controller. In Zend Framework 1 we simply applied a new template via the render()-function of our Controller, but in Zend Framework 2 this has to be done a little differently.

As you may know, when returning variables to the view from your controller you may do it like this

In your view-script (index.phtml) you’d be able to access $this->message (or just $message) and it feels the same way as in Zend Framework 1.

Behind the scenes however there is something happening. The array is transported into a Zend\View\Model\ViewModel and that’s the class responsible for handling the view.

Now if we want to change the view on our controller level we would do it like this:

So what does this do? I tried to find a simple use-case-scenario for why one would have different view-scripts within one action. A login-state is one i could come up with quite fast. In this indexAction() i check if the User is logged in or not with my theoretical functions and assign a depending message for them. When a user is logged in he will be granted the default index.phtml and when a user is not logged in he will be presented the indexloggedout.phtml.

One Template for all Actions

Another simple use-case-scenario was brought up that may require several actions to render the same view. This could be useful and in Zend Framework 1 was basically done by simply setting up the rendered view inside the init()-function of our Controller. In Zend Framework 2 we do no longer have the init()-function but we can simply use the __construct() as pointed out by Matthew W. O’Phinney at his article ZF2′s New Controller::init(). So let’s take a look at that.

Take a look at the constructor and actions. Setters and getters aside, we have a protected $viewModel which we instantiate on __construct(). We set the default.phtml as the view-template to use.

In the actions we simply assign the variables and return the ViewModel. Both actions return the same ViewModel. You can do it in two steps like the indexAction() or on-the-fly like otherAction(), the difference is minimal.

Final words

Hopefully i was able to illustrate how easy it is to change the view-template in Zend Framework 2. If you have different use-cases in where this might come in handy, let me know about it in the comments.

Clip to Evernote
2 Responses to Changing the View Template / View Script
  1. Ron Reply

    Posted a question regarding this post:

Leave a Reply

Your email address will not be published. Please enter your name, email and a comment.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">