国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
format
striptags
escape
Home Backend Development PHP Tutorial Twig - the Most Popular Stand-Alone PHP Template Engine

Twig - the Most Popular Stand-Alone PHP Template Engine

Feb 09, 2025 am 09:07 AM

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

// 實(shí)例化我們的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';

// 創(chuàng)建產(chǎn)品列表
$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');

// 實(shí)例化我們的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';

// 創(chuàng)建產(chǎn)品列表
$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');

// 實(shí)例化我們的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';

// 創(chuàng)建產(chǎn)品列表
$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 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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are some best practices for versioning a PHP-based API? What are some best practices for versioning a PHP-based API? Jun 14, 2025 am 12:27 AM

ToversionaPHP-basedAPIeffectively,useURL-basedversioningforclarityandeaseofrouting,separateversionedcodetoavoidconflicts,deprecateoldversionswithclearcommunication,andconsidercustomheadersonlywhennecessary.StartbyplacingtheversionintheURL(e.g.,/api/v

How do I implement authentication and authorization in PHP? How do I implement authentication and authorization in PHP? Jun 20, 2025 am 01:03 AM

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

What are the differences between procedural and object-oriented programming paradigms in PHP? What are the differences between procedural and object-oriented programming paradigms in PHP? Jun 14, 2025 am 12:25 AM

Proceduralandobject-orientedprogramming(OOP)inPHPdiffersignificantlyinstructure,reusability,anddatahandling.1.Proceduralprogrammingusesfunctionsorganizedsequentially,suitableforsmallscripts.2.OOPorganizescodeintoclassesandobjects,modelingreal-worlden

What are weak references (WeakMap) in PHP, and when might they be useful? What are weak references (WeakMap) in PHP, and when might they be useful? Jun 14, 2025 am 12:25 AM

PHPdoesnothaveabuilt-inWeakMapbutoffersWeakReferenceforsimilarfunctionality.1.WeakReferenceallowsholdingreferenceswithoutpreventinggarbagecollection.2.Itisusefulforcaching,eventlisteners,andmetadatawithoutaffectingobjectlifecycles.3.YoucansimulateaWe

How can you handle file uploads securely in PHP? How can you handle file uploads securely in PHP? Jun 19, 2025 am 01:05 AM

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

What are the differences between == (loose comparison) and === (strict comparison) in PHP? What are the differences between == (loose comparison) and === (strict comparison) in PHP? Jun 19, 2025 am 01:07 AM

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? How can you interact with NoSQL databases (e.g., MongoDB, Redis) from PHP? Jun 19, 2025 am 01:07 AM

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

How do I perform arithmetic operations in PHP ( , -, *, /, %)? How do I perform arithmetic operations in PHP ( , -, *, /, %)? Jun 19, 2025 pm 05:13 PM

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

See all articles