Install Twig (views template) in Slim Framework

Okay from latest post, I created a tutorial about how to use slim framework/first install slim framework. And now I want to share how to install twig for views template in slim. But how to do it?
Okay frist open your slim framework again, and open file composer.json and change to be like this:

    "require": {
        "slim/slim": "~2.6",
        "slim/views": "~0.1",
        "twig/twig": "~1.0"


  1. Line 4 is the package to install twig/smarty in slimframework, more info read this
  2. Line 5 is to install core twig

After you add this code, then run composer update:

$ composer update

And now you already install twig templates and now is to use twig template in slim. First open your slim framework and create file structure like this:

├── App
│   ├── Models
│   └── Views
│       └── hello.html
├── composer.json
├── composer.lock
├── index.php
└── vendor
    ├── autoload.php
    ├── composer
    ├── slim
    └── twig

Or you can look at this image:
Structure slim.
And now you must open index.php file and change the code to be like this:

// Initialize Slim (the router/micro framework used)
require_once 'vendor/autoload.php';

$app = new \Slim\Slim([
		'debug' => true,
		'templates.path' => 'App/Views'

// and define the engine used for the view @see
$app->view = new \Slim\Views\Twig();

// Twig configuration
$view = $app->view();
$view->parserOptions = ['debug' => true];
$view->parserExtensions = [new \Slim\Views\TwigExtension()];

$app->get('/', function () use ($app) {


  1. Line 3 is use to include core of slim
  2. Line 5-8 is to instance/create object from slim framework with debugging is true and add folder for save view file
  3. Line 11-12 is use to instance twig
  4. Line 15-17 is use to config and connect slim with twig template.
  5. Line 19-21 is use to render the view “hello.html” from directory App/views and this is a routing if we use slim. More info you can read on this

And for the last, open file hello.html and write this code:

<!DOCTYPE html>

And now run the code, if you don’t have a error, the result should be like this:

One comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s