search
HomeBackend DevelopmentPHP TutorialTwig - the Most Popular Stand-Alone PHP Template Engine

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>"; ?>

or

<p>Hello {{ name }}</p>

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

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>"; ?>

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>

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

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);

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] );

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>

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>"; ?>

(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>
or letter:

composer require twig/twig
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);

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] );

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

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 %}

striptags

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

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

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>

equivalent to

composer require twig/twig

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);

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] );

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
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
PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.