This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Try the fastest hosting platform with pay-as-you-go pricing & 24/7 expert support! MIGRATE NOW →

Creating Twig Templates in Slim Microframework

Updated on July 15, 2021

7 Min Read

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 PHP website hosting. 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:

$ composer require slim/slim “^3.0”

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:

{

   "require": {

       "slim/slim": "^3.0",

       "slim/twig-view": "^2.2"

   }

 }

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.

$ composer require slim/twig-view

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.

<?php

session_start();

require __DIR__ . '/../vendor/autoload.php';

$app = new \Slim\App([

'settings' => [

       'displayErrorDetails' => true,

]

]);

$app->get('/first', function($request, $response) {

   return 'My first route';

})

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.

<?php

require __DIR__ . '/../bootstrap/app.php';

$app->run();

?>

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.

RewriteEngine On

RewriteCond %{Request_Filename} !-F

RewriteCond %{Request_Filename} !-d

RewriteRule ^ index.php [QSA,L]

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:

RewriteRule ^ public/index.php [QSA,L]

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:

$container = $app->getContainer();

$container['view'] = function ($container) {

   $view = new \Slim\Views\Twig(__DIR__ . '/../resources/views', [

       'cache' => false,

   ]);

   $view->addExtension(new \Slim\Views\TwigExtension(

       $container->router,

       $container->request->getUri()

   ));

   return $view;

};

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

<?php

$app->get('/home', function ($request, $response) {

   return $this->view->render($response, 'home.twig');

})

?>

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:

{

   "require": {

       "slim/slim": "^3.0",

       "slim/twig-view": "^2.2"

   },

   "autoload": {

       "psr-4": {

           "App\\": "app"

       }

   }

}

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:

$ composer dump-autoload -o

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:

<?php

namespace App\Controllers;

use Slim\Views\Twig as View;

class HomeController 

{

   protected $views;

   public function __construct(Views $views)

   {

       return $this->view = $views;

   }

   public function index($request, $response)

   {

      return $this->view->render($response, 'home.twig');

   }

}

?>

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

$container['HomeController'] = function ($container) {

   return new \App\Controllers\HomeController($container->view);

};

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

$app->get('/new', 'HomeController:index');

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:

<?php

namespace App\Controllers;

class BaseController

{
   protected $container;

   public function __construct($container){

       $this->container = $container;

   }
}

?>

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.

<?php

namespace App\Controllers;

use Slim\Views\Twig as View;

class HomeController extends BaseController

{

   public function index($request, $response)

   {

      return $this->container->view->render($response, 'home.twig');

   }

}

?>

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

$container['HomeController'] = function ($container) {

   return new \App\Controllers\HomeController($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.

<nav class="navbar navbar-inverse">

 <div class="container-fluid">

   <div class="navbar-header">

     <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

       <span class="icon-bar"></span>

       <span class="icon-bar"></span>

       <span class="icon-bar"></span>                        

     </button>

     <a class="navbar-brand" href="#">WebSiteName</a>

   </div>

   <div class="collapse navbar-collapse" id="myNavbar">

     <ul class="nav navbar-nav">

       <li class="active"><a href="#">Home</a></li>

       <li class="dropdown">

         <a class="dropdown-toggle" data-toggle="dropdown" href="#">Page 1 <span class="caret"></span></a>

         <ul class="dropdown-menu">

           <li><a href="#">Page 1-1</a></li>

           <li><a href="#">Page 1-2</a></li>

           <li><a href="#">Page 1-3</a></li>

         </ul>

       </li>

       <li><a href="#">Page 2</a></li>

       <li><a href="#">Page 3</a></li>

     </ul>

     <ul class="nav navbar-nav navbar-right">

       <li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>

       <li><a href="#"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>

     </ul>

   </div>

 </div>

</nav>

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:

<!DOCTYPE html>

<html>

<head>

<title>Cloudways</title>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" crossorigin="anonymous"></script>

</head>

<body>

{% include 'templates/navigation.twig' %}

<div class= "container">

   {% block content %}{% endblock %}

</div>

</body>

</html>

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:

{% extends 'templates/app.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.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now