


Introducing Twig: The perfect tool to jump-start your WordPress development
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.
