Twig Tutorials: Install and Configure

In this tutorial we will see how to install Twig inside your PHP project and then configure it so that we can create use Twig template inside our PHP web application.

later we see a simple Twig template example which will display "Welcome to Twig template" message.

lets see each step one by one.


we can install Twig template via Composer, Git or from PEAR.

in this tutorial post we will install Twig using Composer.

for that we need to create "composer.json" file.

    "require": {
        "twig/twig": "1.*"

the from console run following command.

  php composer.phar install   

this command will install Twig library.


To use Twig template we need configure it first, for that we will create index.php file which will setup Twig autoloader and generate the Twig environment.

using this Twig environment we will render Twig template

include __DIR__ . "/vendor/twig/twig/lib/Twig/Autoloader.php";

//register autoloader


//loader for template files

$loader = new Twig_Loader_Filesystem('templates');

//twig instance

$twig = new Twig_Environment($loader, array('cache' => 'cache'));

//load template file

$template = $twig->loadTemplate('index.html');

//render a template

echo $template->render(array('title' => 'Welcome to Twig template'));

now we will create "template.html" file inside template folder.




    <h1>{{ title }}</h1>



and you will get following output when you run index.php file in localhost

That's it, we are done with Twig installation and configuration process.

Source Code

Download source code from this Github link


Popular posts from this blog

AngularJs Tutorial: Getting Started

Abstract Factory design pattern analysis

AngularJs Tutorials : Bootstrap