Home >Backend Development >PHP Tutorial >Introducing Twig: The perfect tool to jump-start your WordPress development

Introducing Twig: The perfect tool to jump-start your WordPress development

PHPz
PHPzOriginal
2023-08-28 20:53:071211browse

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