Pass a model

While view items can be useful to pass generic data, such as the title and so on, the primary data for a page should be passed via a model.

Create the model

Let's get rid of the hard coded author information on our "About"-page and pass it as a model instead. While we're at it, we also add an additional year parameter.

Open Application/Controllers/IndexController.php and modify the aboutAction method to look like this:

public function aboutAction() { $model = ['Name' => 'John Doe', 'Email' => '', 'Year' => 2018]; $this->setViewItem('Title', 'About this website'); return new View($model); }

Anything that is passed as the first parameter to View() is considered to be the model. The parameter name $model is only for illustrative purposes. Also any type or object can be passed as a model.

Display the model

Open Application/Views/Index/about.twig and modify the content like this:

{% extends "sitelayout.twig" %} {% block content %} <h1>About this website</h1> <p class="intro"> This is a website created by {{ Model.Name }} {{ Model.Year }} </p> <p> E-mail me at <a href="mailto:{{ Model.Email }}">{{ Model.Email }}</a> </p> {% endblock %}

Check the result

Reload the http://localhost/about page to see the new result:

Output with model

The array passed to the View constructor in the controller is always available as the Model object in the view.

The dot-notation for accessing array elements as in Model.Name is a Twig functionality. See the Twig variables documentation for more information.

Of course in real life applications, the model content is not hard coded in the controller, but is rather a result from a database query or something similar. We will continue with this in the following parts.

✎ Published in category get started