Using layouts with Twig and SlimPHP

Now that we have Twig integrated, we can start to add multiple routes to our application that all use a common layout. Let’s start by creating a layout for our application to use.

Create views/layout.html with the following contents:

    This is a header
    {% block content %}{% endblock %}
    This is a footer

Usually you’d have head and body tags, but this is enough to show how layouts work. It’s all pretty standard apart from those block and endblock calls in the middle. This is Twig syntax for marking an area as something that can change. In this layout, we can put content in that space by putting it inside a content block.

It’ll make a little more sense once we update our index.html to use this layout. Open views/index.html and replace it’s contents with the following:

{% extends "layout.html" %}

{% block content %}
Hello {{name}}
{% endblock %}

We start by saying that this file extends layout.html (which is what we want), then we see that strange block option again. Everything between the block content and endblock tags will be placed in between our header and footer in layout.html. Save the file, start the PHP server with php -t public -S localhost:8000 and visit http://localhost:8000 and you should see your content in the layout that you designed.

Now that we have a layout, we can create another route and view! Create the view first by adding the following to views/weather.html

{% extends "layout.html" %}

{% block content %}
Today is a sunny day
{% endblock %}

Next, we need a route to render this view. Add the following to public/index.php just before $app->run():

$app->get('/weather', function (Request $request, Response $response) {
    return $this->view->render($response, 'weather.html');

Once again, run the server with php -t public -S localhost:8000 before browsing to http://localhost:8000/weather – you should see the new content in your existing layout. Now, if you update the layout at all it will automatically update every view that you have.

That brings us to the end of our posts on Slim and Twig for now. Next, we’ll be taking a look at how to split our application up in to controllers.

You can find the code for this section on Github

Leave a Reply