Thursday, October 16, 2014

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.

Install


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.


Configuration


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

Twig_Autoloader::register();

//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.

<html>

  <head></head>

  <body>

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

  </body>

</hmtl>

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

Zainul Abedin Shaikh

Founder of Zainabed, Passionate about programming. Follow him on Twitter

And if you enjoyed this post, please consider sharing it on Facebook, Google+ or Twitter below