Home » Twig Tutorials » Setup Twig template engine

Setup Twig template engine

    Installing Twig as a standalone with and without composer. Twig setup as a part of another product such as Symfony, Drupal, Bolt, WordPress or Laravel

    1- Install/setup Twig as a part of another product

    Twig comes as a part of many other products: such as Symfony, Drupal, or Bolt. in this case, we can use Twig directly after installing one of these products

    2- Timber and Twig installation on WordPress

    Timber is a WordPress plugin that uses Twig to render templates. To use Twig on WordPress just install Timber.

    3- Setup Twig with Laravel

    Laravel comes with Composer and with its own templating engine called Blade. Whoever if need to use Twig just run the following command via SSH:

    composer install rcrowe/twigbridge twig/twig

    4- Twig installation with composer

    4-1- Ensure you have SSH access

    First and most important you will need SSH access. If your hosting plan doesn’t include it; you can not use this method.

    4-2- Install Composer

    Using SSH you can install composer on your hosting plan. the steps need may differ according to your hosting company. However, read the flowing article for details
    How to install composer on shared A2 hosting 

    4-3- Twig Setup and Composer

    Run the following command via SSH. This will tell Composer to install the latest version of Twig

    composer require "twig/twig"

    5- Install Twig without composer

    5-1- Download the latest version of Twig via GitHub or this link

    5-2- Extract the files in the compressed zip and open the folder Twig-3.x

    5-3- Inside the above mention folder there is a subfolder called src; rename it to Twig

    5-4- Copy Twig folder to your hosting root public_html directory

    5-5- In public_html create a file index.php and set ist contents as flows

    <?php
    ini_set('display_errors',1); # comment if you do not need debugging
    spl_autoload_register(function ($classname) {
        $dir = '.';
        $filename = $dir . str_replace('\\', '/', $classname) .'.php';
        if (file_exists($filename)) require_once $filename;
    });
    require_once '\Twig\Loader\FilesystemLoader.php';

    Calling Twig template from PHP

    After Twig setup we can start using it. Just add the flowing code to PHP on your page

    <?php
    $loader = new \Twig\Loader\FilesystemLoader('.');
    $twig = new \Twig\Environment($loader);
    echo $twig->render('template1.twig', [‘name’ => 'سامر']);

    In the same folder create 'template.twig' file and write the code:

    Twig

    Helo Student {{ name }}

    Conclusion

    We discuss how to install Twig and how to call it. In the next article, we will discuss the Twig template syntax and how to use it.

    End