Home > Backend Development > PHP Tutorial > Twig - the Most Popular Stand-Alone PHP Template Engine

Twig - the Most Popular Stand-Alone PHP Template Engine

Lisa Kudrow
Release: 2025-02-09 09:07:11
Original
893 people have browsed it

Twig - the Most Popular Stand-Alone PHP Template Engine

Twig: A popular PHP template engine

Twig is a popular PHP template engine developed by Sensio Labs. It simplifies PHP code and adds features such as security and debugging. Twig acts on both frontend and backend of the project, and can be viewed from two perspectives: Twig for template designers and Twig for developers. Twig uses a core object named Environment to store configurations, extensions, and load templates from a file system or elsewhere. Twig supports nested templates (blocks), avoiding duplication of elements in templates, and can cache compiled templates to speed up subsequent requests. Twig supports conditional statements, loops and filters to control the display of information in templates and provides debugging capabilities to dump all information about template variables.

This article was peer-reviewed by Wern Ancheta. Thanks to all the peer reviewers of SitePoint for getting SitePoint content to its best!


Twig is PHP's template engine. But isn't PHP itself a template engine? Yes, not! Although PHP was originally used as a template engine, it did not develop, and although we can still use it as a template engine, which version of "Hello world" do you prefer:

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

or

<p>Hello {{ name }}</p>
Copy after login
Copy after login
Copy after login
Copy after login

PHP is a verbose language that is amplified when trying to output HTML content. Modern template systems will eliminate partial verboseness and add quite a bit of functionality to it. Features such as security and debugging capabilities are the backbone of modern template engines. Today, we will focus on Twig.

Twig - the Most Popular Stand-Alone PHP Template Engine

Twig is a template engine created by Sensio Labs (the development company of Blackfire and Symfony). Let's take a look at its main advantages and how to use it in your project.

Installation

There are two ways to install Twig. We can use the tar packages available on their website, or use Composer as we have been doing.

composer require twig/twig
Copy after login
Copy after login
Copy after login
Copy after login

We assume you are running an environment where PHP is set up and Composer is installed globally. The best way is to use Homestead Improved – it allows you to start using it in 5 minutes on the exact same machine we use so we can be on the same page. If you want to learn more about the PHP environment, we have an excellent paid book about this here for purchase.

We need to clarify something before we can continue. As a template engine, Twig acts on both frontend and backend of the project. So we can look at Twig from two different perspectives: Twig for template designers and Twig for developers. On the one hand, we prepare all the data we need; on the other hand, we present all of this data.

Basic Usage

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

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

Twig uses a core object named Environment. Instances of this type are used to store configurations, extensions, and load templates from file systems or other locations. After our Twig instance boots, we can go ahead and create a index.php file where it loads some data and passes it to the Twig template.

<p>Hello {{ name }}</p>
Copy after login
Copy after login
Copy after login
Copy after login

This is a simple example; we are creating an array containing products, such as our mechanical keyboard, which we can use in templates. Then we use the render() method, which accepts the template name (this is a file in the template folder we defined earlier) and the data we want to pass to the template. To complete our example, let's go to our /templates folder and create a index.html file. First, let's look at the template itself.

composer require twig/twig
Copy after login
Copy after login
Copy after login
Copy after login

Open index.php in your browser (visit localhost or homestead.app, depending on how you set up the host and server) should now display the following screen:

Twig - the Most Popular Stand-Alone PHP Template Engine

But let's go back and take a closer look at our template code. There are two types of separators: {{ ... }} is used to print the results of an expression or operation, while {% ... %} is used to execute statements such as conditional statements and loops. These delimiters are the main language structure of Twig, which Twig uses to "inform" the template it must render the Twig element.

(The following content is similar to the original text, but some statement adjustments and paragraph divisions have been made, and the image position remains unchanged)

Layout

To avoid duplicating elements (such as headers and footers) in templates, Twig allows us to nest templates in templates, which are called blocks. To illustrate this, let's separate the actual content from the HTML definition in the example. Let's create a new HTML file and name it layout.html:

<?php
// 加载我们的自动加载器
require_once __DIR__.'/vendor/autoload.php';

// 指定我们的Twig模板位置
$loader = new Twig_Loader_Filesystem(__DIR__.'/templates');

// 实例化我们的Twig
$twig = new Twig_Environment($loader);
Copy after login
Copy after login
Copy after login

We created a block called content. We mean that each template extending from layout.html can implement a content block, which will be displayed at that location. This way, we can reuse the layout multiple times without rewriting it. In this case, the index.html file now looks like this:

<?php
require_once __DIR__.'/bootstrap.php';

// 创建产品列表
$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',
    ],
];

// 渲染我们的视图
echo $twig->render('index.html', ['products' => $products] );
Copy after login
Copy after login
Copy after login

Twig also allows us to render only single blocks. To do this, we need to load the template first and then render the block.

<!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>
            {% for product in products %}
                <tr>
                    <td>{{ product.name }}</td>
                    <td>{{ product.description }}</td>
                    <td>{{ product.value }}</td>
                    <td>{{ product.date_register|date("m/d/Y") }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    </body>
</html>
Copy after login
Copy after login

At this point, we still have the same page, but we reduce its complexity by decoupling the context blocks.

Cache

EnvironmentObjects can not only be used to load templates. If we pass using the cache option of the associated directory, Twig will cache the compiled template, thus avoiding parsing the template in subsequent requests. The compiled template will be stored in the directory we provide. Note that this is the cache for the compiled templates, not the cache for the evaluated templates. This means that Twig will parse, compile and save the template file. All subsequent requests still require evaluation templates, but the first step is already done for you. Let's cache the template in the example by editing the bootstrap.php file:

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

(The following content is similar to the original text, but some statement adjustments and paragraph divisions have been made, and the image position remains unchanged)

Cycle

In our example, we have seen how to loop with Twig. Basically, we use the for tag and assign an alias to each element in the specified array. In this case, we assign an alias to the products array. After that, we can use the product operator to access all properties in each array element. We use the . tag to indicate the end of the loop. We can also loop through numbers or letters using the endfor operator. As shown below: ..

<p>Hello {{ name }}</p>
Copy after login
Copy after login
Copy after login
Copy after login
or letter:

composer require twig/twig
Copy after login
Copy after login
Copy after login
Copy after login
This operator is just the syntax sugar of the

function, and it works the same way as the native PHPrange function. An equally useful option is to add conditions to the loop. Using conditions, we can filter the elements to iterate. Suppose we want to iterate over all products with a value less than 250: range

<?php
// 加载我们的自动加载器
require_once __DIR__.'/vendor/autoload.php';

// 指定我们的Twig模板位置
$loader = new Twig_Loader_Filesystem(__DIR__.'/templates');

// 实例化我们的Twig
$twig = new Twig_Environment($loader);
Copy after login
Copy after login
Copy after login

Conditional statement

Twig also provides conditional statements in the form of

, if, elseif and if not tags. Just like in any programming language, we can use these tags to filter conditions in templates. Suppose in our example, we want to display only products with a value above 500: else

<?php
require_once __DIR__.'/bootstrap.php';

// 创建产品列表
$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',
    ],
];

// 渲染我们的视图
echo $twig->render('index.html', ['products' => $products] );
Copy after login
Copy after login
Copy after login

Filter

Filters allow us to filter the information passed to the template and the format of the information displayed. Let's take a look at some of the most commonly used and important filters. A complete list of Twig filters can be found here.

Date and

date_modify

Filter formats the date to the given format. As we see in the example: date

<!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>
            {% for product in products %}
                <tr>
                    <td>{{ product.name }}</td>
                    <td>{{ product.description }}</td>
                    <td>{{ product.value }}</td>
                    <td>{{ product.date_register|date("m/d/Y") }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
    </body>
</html>
Copy after login
Copy after login
We display dates in month/day/year format. In addition to the

filter, we can also use the date filter to change the date using the date_modify filter. For example, if we want to add a day to a date, we can use the following:

<!DOCTYPE html>
<html lang="pt-BR">
    <head>
        <meta charset="UTF-8">
        <title>Tutorial Example</title>
    </head>
    <body>
        {% block content %}
        {% endblock %}
    </body>
</html>
Copy after login

format

Format the given string by replacing all placeholders. For example:

{% extends "layout.html" %}

{% block content %}
    <table> border="1" style="width: 80%;">
        <thead>
            <tr>
                <td>Product</td>
                <td>Description</td>
                <td>Value</td>
                <td>Date</td>
            </tr>
        </thead>
        <tbody>
            {% for product in products %}
                <tr>
                    <td>{{ product.name }}</td>
                    <td>{{ product.description }}</td>
                    <td>{{ product.value }}</td>
                    <td>{{ product.date_register|date("m/d/Y") }}</td>
                </tr>
            {% endfor %}
        </tbody>
    </table>
{% endblock %}
Copy after login

striptags

striptags The filter removes SGML/XML tags and replaces adjacent spaces with spaces:

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

escape

escape is one of the most important filters. It filters the string to insert safely into the final output. By default, it uses HTML escape policy, so

<p>Hello {{ name }}</p>
Copy after login
Copy after login
Copy after login
Copy after login

equivalent to

composer require twig/twig
Copy after login
Copy after login
Copy after login
Copy after login

js, css, url, html_attr and

escape policies are also available. They are Javascript, CSS, URI, and HTML attribute context escape strings, respectively.

Debug

dump() Finally, let's take a look at debugging. Sometimes we need to access all the information of the template variable. To do this, Twig has a Twig_Extension_Debug function. This function is not available by default. When creating a Twig environment, we have to add the

extension:
<?php
// 加载我们的自动加载器
require_once __DIR__.'/vendor/autoload.php';

// 指定我们的Twig模板位置
$loader = new Twig_Loader_Filesystem(__DIR__.'/templates');

// 实例化我们的Twig
$twig = new Twig_Environment($loader);
Copy after login
Copy after login
Copy after login

dump()This step is necessary so that we do not accidentally leak debug information on the production server. Once the configuration is complete, we simply use the

function to dump all information about the template variables.
<?php
require_once __DIR__.'/bootstrap.php';

// 创建产品列表
$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',
    ],
];

// 渲染我们的视图
echo $twig->render('index.html', ['products' => $products] );
Copy after login
Copy after login
Copy after login

Conclusion

I hope this article will provide you with a solid foundation for Twig basics and start your project right away! If you want to have a deeper look at Twig, the official website provides very good documentation and references that you can check out. Do you use the template engine? What do you think of Twig? Would you compare it to popular alternatives like Blade or Smarty?

(The following content is FAQ, the original text has been included, omitted here)

The above is the detailed content of Twig - the Most Popular Stand-Alone PHP Template Engine. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template