search
HomeBackend DevelopmentPHP TutorialIntroducing Twig: The perfect tool to jump-start your WordPress development

Twig 简介:快速启动 WordPress 开发的完美工具

Much has been written about the future of WordPress, with many arguing that it lacks a template language, especially when platforms like Django, Ruby on Rails, Node.js, Laravel and even Drupal have templates language time. Facts like “WordPress powers nearly 25% of the web” makes it hard to question its current PHP-based templating system. But since modularity in the code is still missing, one can ask when the core will have a template engine.

The good news is here! The Twig template engine and a plugin called Timber help us write super clean and modular code in WordPress. In this series, we will discuss its implementation and integration with WordPress. I’ll start with the basics of what Twig is and why you need it, and over the next three articles I’ll explain the different types of Twig templates that integrate with WordPress through Timber.

What is a branch?

Twig is a flexible, fast and secure PHP template engine. Twig is brought to you by Fabien Potencier, the creator of the Symfony framework, and is considered feature-rich, extensive, fast, and efficient.

Typically when you code in WordPress, you mix PHP chunks with HTML (this is what we call spaghetti code). This is not a super clean mark. In order to adopt a modular and Doing it Right™ approach, View needs to be separated from Data. Using Twig, you can separate the view layer from the rest of the application. Twig adopts the Model-View-Controller (MVC) pattern, which helps maintain clean code.

Why use Twig?

Over the years, different PHP template engines have been developed, but Twig definitely surpasses them all in the following capabilities.

Rich functions

Twig is one of the most feature-rich and powerful PHP template engines. It supports multiple inheritance and automatic output escaping, and helps divide templates into multiple blocks or components to maintain a modular design. Not only that, developers can add more plugins to meet any front-end needs.

Fast and efficient

Templates compiled with Twig bear much less overhead than regular PHP templates. Coding routines are highly optimized and you save a lot of development time. It is also useful when you plan to change the base framework, as Twig can help create a separate template layer that can be connected with any backend framework, whether it is Laravel or WordPress.

Designer and Developer Friendly

Twig suits the requirements of designers and developers. Even if you're not a coding geek, using Twig is easy, and writing modular templates based on components feels right. Its syntax is easy to understand and avoids implementing dynamic PHP operations in template files. All in all, it is very modern and works with all the latest coding standards. The concept of output escaping is very comprehensive when processing with Twig.

Let's start with a simple example.

In regular PHP you would get output like this:

<?php echo $foo;  // $foo is any random variable ?>
<?php echo htmlspecialchars( $foo, ENT_QUOTES, 'UTF-8' ) ?>

In Twig, things are even simpler, that is, the above code is condensed to:

{{ foo }}       
{{ foo|escape }}
{{ foo|e }}         {# shortcut to escape a variable #}

Output escaping is that simple in Twig. Just add double curly braces, enter the name of the variable and you will get the output. Put a pipe with e next to it and we start escaping. The next three articles in this series will cover this in detail.

Safety

Twig cleans and protects data itself. Its unique Sandbox mode can intelligently monitor the entire code and filter out the best results. This means user-generated templates can be implemented easily and securely. The sandbox environment can only be enabled globally or locally for a specific template, as follows:

{{ include( 'post.html', sandboxed = true ) }}

If any syntax errors occur, Twig will generate a message to debug your file with details such as the file name and the line number of the offending code.

flexible

I just mentioned that Twig is a modern template engine, which also means that you can extend its functionality because it is very flexible. It fully supports efficient lexical analyzers and parsers, through which developers can define custom tags, filters, functions, etc.

other

In addition to all the features mentioned above, Twig is well documented and fully unit tested. Its API and template library are fully stable and can handle a variety of complex tasks. A dedicated online book and complete API documentation are also available.

Twig is the new templating language for Drupal 8, which is my main motivation for using this templating engine with confidence. The good folks at XWP, especially Weston Ruter, are working on a proposal to make Twig compliant with WordPress.com VIP standards.

Timber: Integrating Twig with WordPress

The entire discussion so far has revolved around two things. First, we should take a modular approach and separate templates from data when building custom WordPress themes, and second, Twig can help us do this. But what brings these two together?

Different efforts have been made to achieve the best integration between Twig and WordPress, one of the brave attempts is Timber created by a web agency called Upstatement. It uses the Twig template engine, which makes it possible to write modular and clean code in WordPress.

Timber and Twig help you build fast and modular WordPress themes. This allows you to separate HTML code from regular PHP files, ensuring a more sustainable coding pattern. The concept of separating HTML and PHP allows PHP files to focus strictly on providing data and logic, while HTML files (Twig files) focus on the view Web application layer.

In general, Timber performs three main tasks:

  • It integrates Twig into WordPress.
  • It renders Twig templates.
  • It adds base WordPress datasets.

I think their mission statement says it all:

Timber is a tool for developers who want to convert HTML into high-quality WordPress themes through an intuitive, consistent, and fully accessible interface.

  • Intuitive: The API is written with the user at the center and around the expectations of programmers.
  • Consistent: All WordPress objects are accessible through polymorphic properties such as slug, ID, and name.
  • Accessible: No black box. We've made every effort to make 100% of HTML accessible to developers.

How does wood work?

For regular WordPress themes, all PHP and HTML code snippets are integrated and modified in the same PHP template file. However, with Timber, we split the template file into two different data files: the PHP file and the view/template file, the Twig file.

So the first file has the extension .php and the second file has the extension .twig. So if you were to create template files for single.php, your files would be named single.php and single.twig.

The former is a file that organizes data, and the latter is a template that uses data in HTML. This way you can add dynamic actions in your WordPress theme in a modular way.

Let’s sum it up:

Timber handles WordPress theme template files in PHP and HTML (Twig) files. This way you can separate logic from display. It gives you new ways to build, design and display your themes.

in conclusion

There’s a lot to love about Twig. This article just introduces the advantages of using a template engine in WordPress. Modular code is better code and easier to maintain. It’s time for developers to make a workflow shift, and I believe Twig can help them do just that.

In the following article, I will show the actual implementation using Twig template files. We'll look at how to implement Twig to render WP images, comments, and menus with code examples. Until then, if you find any doubts, please feel free to ask. Don’t forget to connect with us on Twitter.

The above is the detailed content of Introducing Twig: The perfect tool to jump-start your WordPress development. 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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

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

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.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools