Slim PHP 101 - How to use multiple view parsers

Posted by Andrew Smith

April 10, 2014

In this post we will go through setting up Slim to work with multiple view parsers, for this example we will look at using Slim’s PHP view library and the Twig view library. In order to use Slim with Twig we need a view parser, luckily enough there is already one created in the Slim Views repository.

Step through index.php code above

Now we are injecting a dependency into the Slim DI container, which we will use as a resource locator later on. If you have a look into the Slim.php source code you will see this being used for quite a few dependencies inside of Slim itself. We are setting this as a singleton because we want the resource definition to remain each time it is requested.

In the singleton method we define our resource as twig and pass it a closure with our settings and extensions we want to load. The first piece of code inside of our closure is just instantiating the Twig view.

<?php
$twig = new \Slim\Views\Twig();

Now we have our Twig view initialised, we might want to setup our options and extensions we want Twig to use. This is what the lines below are doing:

Some more about me

You can find me on various social networks. I tend to tweet about technology a lot on
Twitter, while creating projects and contributing to
open source on Github or when I feel a bit creative I
jump on Dribbble.