Display content from a view

We have now managed to create a new page that displayed the output from an action method.

The next step is to separate the html-content from the controller code. This will be done by returning a View from the action method.

Create the view

Modify the aboutAction method to return a new View object:

/** * The index controller class. */ class IndexController extends Controller { /** * The index action. * * @return View The view for this action. */ public function indexAction() { $this->setViewItem('Title', 'My website'); return new View(); } public function aboutAction() { return new View(); } }

Again, navigate to the url http://localhost/about and check the result:

Could not find view file

Well, that did not work! ╯°□°)╯︵ ┻━┻

When returning a View, a corresponding view file with the content to be displayed must be present in the Views directory.

Create a new file about.twig in the directory Application/Views/Index/ with the following content:

<h1>About this website</h1> <p class="intro"> This is a website created by John Doe </p> <p> E-mail me at <a href="mailto:info@example.com">info@example.com</a> </p>

The default path for a view file is in the Views directory, with the name of the controller as a subdirectory, containing a file with the name of the action method, e.g. IndexController + aboutAction resolves to Views/Index/about.twig.

Check the result

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

About this website

┬──┬◡ノ(° -°ノ)

Not much has changed visually yet, but in the next part the look of our new page will be improved.

✎ Published in category get started