Steps to use Twig template engine in PHP applications

Himanshu BatraFeb 20, 2020
Steps to use Twig template engine in PHP applications

Working with twig template engine is very interesting because it provides a clean template structure to render optimized PHP output which used for rendering HTML output. Twig was designed and developed by Symfony developers. Twig files are having extension of .html.twig which is a mixup of twig constructs & static HTML code. Here are some syntax of twig :

  • For Output : Double curly brace {{ }}
  • For Logic : Curly brace with percentage {% %}
  • For Comments : Curly brace with hash{# #}

Example Syntax :

    {% for item in items %}
        <p>{{ item }}</p>
    {% endfor %}

Now, we are going to elaborate steps for using twig template engine in your next PHP application without any hassel of code complications.

Step 1: Create PHP Application

Initially, we need to build a PHP application in htdocs folder of server i.e.localhost with name i.e. etuts.

PHP Application

After creating this folder, create a php script file i.e. index.php inside this application folder.

Step 2: Twig Setup

Inside application folder, we have to setup twig templating engine by using composer command.

composer require "twig/twig"

Twig by Composer

After successful installation of twig package, we'll create a template folder named as "templates" inside our application. In templates folder, we'll create a twig extension file i.e. render.html.twig which will connect with php code and render output as html code.

Reference code for using php values inside twig template.

Hello, My name is {{ name }} and i am from {{ city }}


Step 3: Call Twig Package inside PHP

Here, we'll call autoload file i.e. autoload.php of twig package inside our php scipt i.e. index.php by following code :

require __DIR__ . '/vendor/autoload.php';
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
$loader = new FilesystemLoader(__DIR__ . '/templates');
$twig = new Environment($loader);
echo $twig->render('render.html.twig', ['name' => 'Kevin Layland','city' => 'Sydney']);

Now, your folder structure will looks like this :

PHP Application Folder Structure

Now, you are ready with your application to run in browser.