Monday, July 31, 2017

Twig – the Most Popular Stand-Alone PHP Template Engine

Twig is a template engine for PHP. But isn't PHP itself a template engine?

Yes and no!

Even though PHP started as a template engine, it didn't evolve like one, and while we can still use it as one please tell me which version of "Hello world" you prefer:

<?php echo "<p> Hello " . $name . "</p>"; ?>

or

<p> Hello  </p>

PHP is a verbose language, and that verbosity is amplified when trying to output HTML content.

Modern template systems will take away some of that verbosity and still add a fair share of functionality on top. Things like security and debug features are mainstays in modern template engines.

Today, we're focusing on Twig.

Twig logo

Twig is a template engine created by Sensio labs, the company behind Blackfire and Symfony. Let's take a look at its main strengths and how can we use it in our projects.

Installation

There are two ways of installing Twig. We can use the tar ball available on their website, or we can use Composer, just like we always do and recommend.

composer require twig/twig

We're assuming you're running an environment with PHP set up and Composer globally installed. Your best bet is using Homestead Improved - it'll let you get started in 5 minutes on the exact same machine we're using, so we're all on the same page. If you'd like to learn more about PHP Environments, we have an excellent premium book about that available for purchase here.

Before we go any further, there's something we need to clarify first.

As a template engine, Twig operates both on the front and on the back end of a project. Because of that, we can look at Twig in two different ways: Twig for template designers and Twig for developers.

On one side, we prepare all data we need. On the other side, we render all that data.

Basic Usage

To exemplify the basic usage of Twig, let's create a simple project. First of all, we need to bootstrap Twig. Let's create a bootstrap.php file with the following content:

<?php

// Load our autoloader
require_once __DIR__.'/vendor/autoload.php';

// Specify our Twig templates location
$loader = new Twig_Loader_Filesystem(__DIR__.'/templates');

 // Instantiate our Twig
$twig = new Twig_Environment($loader);

Twig uses a central object called Environment. Instances of this class are used to store the configuration, extensions, and to load templates from the file system or other locations.

With our Twig instance bootstrapped, we can go on and create an index.php file where we will load some data and pass it to a Twig template.

<?php

require_once __DIR__.'/bootstrap.php';

// Create a product list
$products = [
    [
        'name'          => 'Notebook',
        'description'   => 'Core i7',
        'value'         =>  800.00,
        'date_register' => '2017-06-22',
    ],
    [
        'name'          => 'Mouse',
        'description'   => 'Razer',
        'value'         =>  125.00,
        'date_register' => '2017-10-25',
    ],
    [
        'name'          => 'Keyboard',
        'description'   => 'Mechanical Keyboard',
        'value'         =>  250.00,
        'date_register' => '2017-06-23',
    ],
];

// Render our view
echo $twig->render('index.html', ['products' => $products] );

This is a simple example; we are creating an array of products that we can use in our template. Then, we use the render() method which accepts a template name (this is a file inside the template folder that we defined earlier) and the data that we want to pass to the template.

To complete our example, let's go inside our /templates folder and create an index.html file. First, let's take a look at the template itself.

<!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <title>Twig Example</title>
    </head>
    <body>
    <table border="1" style="width: 80%;">
        <thead>
            <tr>
                <td>Product</td>
                <td>Description</td>
                <td>Value</td>
                <td>Date</td>
            </tr>
        </thead>
        <tbody>
            
        </tbody>
    </table>
    </body>
</html>

Opening index.php in the browser (by visiting localhost or homestead.app, depending on how you've set up your hosts and server) should produce the following screen now:

Rendered table

But let's go back and take a closer look at our template code.

Continue reading %Twig – the Most Popular Stand-Alone PHP Template Engine%


by Claudio Ribeiro via SitePoint

No comments:

Post a Comment