View templates in Alloy are simple PHP templates with built-in helpers for doing common things like creating links from defined routes through reverse matching and adding javascripts and stylesheets to the head of an HTML document. View templates are typically represented within Alloy as an \Alloy\View\Template object that wraps functionality over a specific template and then renders it when an HTTP response is sent.

Alloy view objects are rendered on __toString at the last possible second they have to be. This allows a good amount of flexibility because the view object can be passed around and altered as needed before display. This also allows views and templates to be easily nested - views can be passed into (or instantiated within) other views.

Within The Controller

View objects are typically returned by a controller action to produce an HTTP response. If you are within a controller, there is a special 'template' function available to you that will automatically set the module view path and choose the correct format based on the request. Usage would look something like this:

namespace Module\Home; class Controller extends \Alloy\Module\ControllerAbstract { public function indexAction(\Alloy\Request $request) { $foo = "bar"; $page = $request->page; # Renders app/Module/Home/views/indexAction.html.php return $this->template(__FUNCTION__) ->set(compact('foo', 'page')); } }

The 'indexAction' method is actually returning an object (instance of \Alloy\View\Template) instead of an immediately rendered content string. This allows the template to be further modified before rendering if needed by other parts of your application, like internal HMVC sub-requests.

Within The View

Since view templates in Alloy are native PHP files, they are very easy to work with, and there is no special syntax to learn. Variables passed to the view can be accessed directly by the same variable name they are set with, as expected.

<h2>My Page Title</h2> <p>Foo: echo $foo; ?></p> <p>Page: echo $page; ?></p>


Related Links