Use the sitelayout

Now that we have moved the html-code to a view file, it's time to adapt it to use the site-specific layout.

Extend the sitelayout

The sitelayout is a template that contains the main structure of the website. Our recently created view about.twig will now be made to extend this sitelayout.

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

{% extends "sitelayout.twig" %} {% block 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=""></a> </p> {% endblock %}

By default, BlueMvc uses the Twig template engine to render the views. For more information about extending views with Twig, see the extends tag documentation.

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

About this website

That certainly looked better!

Modify the sitelayout

We will now add a link to the new page in the upper menu bar.

Open the Application/Views/sitelayout.twig file and add the "About"-link:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="/css/styles.css"> <title>{{ ViewItems.Title }}</title> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div class="menu"> <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> </ul> </div> <div class="main"> {% block content %}{% endblock %} </div> </body> </html>

Again, reload the http://localhost/about page:

About this website

The "About" link is now added to the menu. Because it was added to the sitelayout, it will also show up on the index page (and every future page that will extend the sitelayout).

Set a view item

Something is still missing: The browser title.

Empty title

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

public function aboutAction(): View { $this->setViewItem('Title', 'About this website'); return new View(); }

Once more, reload the http://localhost/about page:

About this page

When setting a view item with the setViewItem method in the controller, it will be accessible in the view via the ViewItems property.

In this case the sitelayout uses the Title view item to set the title as seen in the Application/Views/sitelayout.twig file:

<title>{{ ViewItems.Title }}</title>

A view item value can contain any valid PHP type or object, while the name must be a string.

Another way to pass data from the controller to the view is by using a model. This will be covered in the next part.

✎ Published in category get started