Creating Twig Templates in Slim Microframework

by Shahroze Nawaz  April 25, 2017

Slim is a PHP microframework that is ideal for rapid application development. Developers prefer Slim for creating cross-device APIs. Previously, I created a Slim based REST API to show how you can create HTTP requests with Slim and return a JSON response.

You should know Slim is not an MVC framework, so it does not provide a view layer like other MVC frameworks. Slim claims:

Slim’s “view” is the HTTP response.

slim twig template

This means that each route in the Slim is responsible for preparing and returning the response object through which you can render the views. The challenge here is to render a view or a template in Slim?

In this article, I will create and render Twig templates in Slim framework with advanced controller routing. Twig is a modern templating engine for PHP.

Quickly Setup Slim & Twig-view  

The first step is to set up Slim on Cloudways. Simply sign up and launch a PHP application. Check out the following GIF for more information:

Next, open SSH terminal (or puTTY SSH) on Cloudways. To install Slim, run the following command:

This command will install the latest stable version of Slim 3.x . Alternatively, you can also install Slim by adding the dependency in composer.json:

Now run the composer install command to download the latest binaries of the Slim framework. You should see the vendor folder and the composer files in the Project folder.

To render Twig templates in Slim, you need a twig-view component created especially for this purpose. So, in the root directory, run the following command to install it.

This will install twig component from packagist. Now to use it, I will setup a directory structure

Setting Up the Directory Structure

To sort things out, I have setup the following directory structure to meet the basic standards of the project:

At first, all these files and folder might confuse you. However, I will explain the basics of templating and then try to create a MVC type structure in which I will call templates directly from the controllers.

I will start by creating app.php in the bootstrap folder and index.php,.htaccess files in the public folder.   

Create Basic Route & Initialize Slim

Here is how to initialize Slim and create the first basic route. To make things better, I will also add some settings in app.php file.

This “requires” the autoloader and initializes Slim with error display to be true. I have created a basic route which will return a simple string.

Now open index.php from the public folder and add the following code to it.

At this point, when you run the application, you will get the following response:

You might be interested in: Using Eloquent ORM With Slim

Create .htaccess File for Clean URL Structure

To make your life easier, you should create a .htaccess file that defines a clean URL structure. In the public directory, make a .htaccess file and add the following code in it.

This will provide a clean URL structure for the PHP file. (this just means that you don’t have to include PHP filenames in the URL calls). If the index file is located in a different folder (for instance, the public folder) and the .htaccess file is on the root, you can insert the full path of the index file in the last line:

Working with twig-view For Rendering Views

Before setting up things, I have already installed twig-view component.

For keeping views in a separate directory I have created a resources -> views folder which contains all the templates. For rendering views, I need to attach them to Slim’s container. I will get the slim container and tell it where the views are located to return them whenever they are needed. I will also add an extension which generates URL for different routes.

Open app.php file and add the following code to it:

Now in route.php file, add the following code:

Since I have already created home.twig in resources -> views. Add any random string to it like “Rendering from home.twig file”.  Run the /home URL in the browser. You should get:

So the home.twig view is rendering perfectly. This is very basic template rendering.

I will now show you how to render templates through controllers.

Render Templates via Controllers

When working with controllers, models and middlewares, you need to automatically load the files. Slim uses the PSR-4 autoload to perform autoloading. For this, edit composer.json like this:

Add the files you wish to autoload in the autoload object. This object will also describe how these files will be autoloaded. You need to choose the application name which can be anything. For simplicity, I have given the name (App) and the directory name (app) from where the files will be autoloaded.

Lastly, you need to run the dump-autoload command in SSH terminal:

This will generate optimized autoload files in the app folder. Let’s see how the twig templates render from the controller.

Create Controllers & Bind Them to the Container

In Controllers folder, create HomeController.php and add the following code to it:

As the views are available in the Slim container, pass them with HomeController while binding the controller to the container in app.php:

Now in route.php, declare the route like this:

At this point, when you run the /new URL, you should get the view:

The controller is calling the home.twig template perfectly.

Create A Base Controller To Get the Entire Container

If you have work with any MVC framework previously, you know that there is always a base controller to keep things clean. In the above example, I used a constructor which make the view to HomeController available.

Why not keep the controllers clean and create a basic controller class which contains the entire container (available to any new controller as well). To do this create a BaseController.php file in the Controllers folder and add the following code:

Now I will extend my HomeController with BaseController and remove the constructor. Also, the views now exist in the container, so it will be added to the returning view.

Also remove the views from the controller binding and pass only $container:

I will run the same /new route and see if it works:

It is working as I expected.

Exploring Twig Templates

Slim provides great flexibility in terms of twig templates. You can create any template for any purpose ( navigation, body content, etc). You can also create a base template and extends another template from it.

Let’s create a folder templates in the views folder and add two files app.twig and navigation.twig in it.

app.twig will be the base template.

Now add the following bootstrap navigation code in navigation.twig. I grabbed the code straight from the bootstrap website.

app.twig is the base template and contains the necessary script (bootstrap CDN files in this case) and the content block so that any file which extends from this have to define the content block. Of course, the navigation.twig template will also be included in the body. Add the following code to app.twig template:

I am calling home.twig in the controller.Extend it with the base template and add the following line at the top of home.twig:

Finally, run the application in the browser. You should get the bootstrap navigation.

This means that the templating I have created above is working perfectly.

Final Words

In this article, I offered a detailed explanation of how you can create twig template in Slim microframework. I also discussed how you could render the templates in routes and controllers. I also discussed the creation of an MVC type structure in Slim through the directory structure. I have created controllers base templates and config files as you find them in a proper MVC framework.

If you have any question or queries, you can leave a comment below and I will get back to you ASAP.

Create PHP websites without the worry of server management.

Deploy your PHP app on optimized PHP hosting servers.

About Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. He’s always in search of new frameworks and methods to implement them. Besides his coding life, he loves movies and playing soccer with friends. You can email him at shahroze.nawaz@cloudways.com

Stay Connected:

You Might Also Like...