Using layouts with Twig and SlimPHP

This is part 3 of 6 in the "SlimPHP Introduction" series

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:

<header>
    This is a header
</header>
<section>
    {% block content %}{% endblock %}
</section>
<footer>
    This is a footer
</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

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

Leave a comment?

Leave a Reply