Kick-Start WordPress Development With Twig: Blocks, Nesting, and WP Cheatsheet

In the previous article, I wrote about integrating the Twig templating engine with WordPress through Timber and how developers can send data from the PHP files to the Twig files. Let’s discuss how to create a base template with Twig, the benefits of this DRY technique, and a Timber-Twig WordPress Cheatsheet.

Creating a Base Template in Twig

Twig works with the DRY (Don’t Repeat Yourself) principle. One of the most important features of Twig is base templating with nesting and multiple inheritance. While most people use PHP includes in a linear fashion, you can create infinite levels of nested blocks to particularly control your page templates. 

Think of your base template as a parent template with sets of blocks inside it. A child template can extend a parent template and modify any block or blocks from inside it without rewriting the code, which would be similar in both templates.

Let’s take a look at an example parent or base template, a base.twig file. You can place it with other Twig templates in the views folder. You call this file inside any of your Twig templates where it’s used as a parent template for that particular Twig file. Type the following lines of code to create a  views folder. This base template will provide a base structure for your WordPress theme. Here’s the code of a simple base.twig file.

Comments in Twig: # Base Template: base.twig #

You can write comments in Twig with # comment here # syntax. To comment out part of a line in a template, use the comment syntax # … #. This is useful for debugging or to add information for other template designers or yourself. You can find a comment on line #1.

Blocks: % block html_head_container % % endblock %

The entire philosophy of Twig and Timber revolves around the modular code approach in WordPress. I’ve been repeatedly writing about the idea that the data in Twig is handled in the form of components or blocks. 

Blocks are used for inheritance and act as placeholders and replacements at the same time. They are documented in detail in the documentation for the extends tag.

% block add_block_name_here % Blocks content here  % endblock %

In the above-written code, you can find a block called html_head_container which spans line #3 to line #7. Any template that extends this base.twig base template can either inherit the same block’s content or modify it to add something else. There’s another block called content % block content % at which spans line #13 to line #18.

Similarly, the concept of creating blocks is extended further where you can create infinite levels of nested blocks as well. This is the true DRY principle.

Include Statement: % include "header.twig" % 

Twig templates can include other Twig templates, just as we do it in PHP. This base.twig file is going to be a general wrapper, and it is incomplete without its header and footer files. Therefore, the syntax % include "file.twig" % will help us include two different Twig templates:

  • The header template  % include "header.twig" % on line #5.
  • The footer template (% include "footer.twig" % on line #23.

Extending the Base Template

We created a base.twig file as a parent template and left the content block empty. This block can be used inside any custom Twig files which would modify it, and the rest of base template will be inherited as is. For example, let’s create a single.twig file which will extend the base.twig template and will modify the content block.

This code shows a custom single.twig file. On line #3, this template is extending to base.twig as its parent or base template. The extends tag can be used to extend a template from another one.

Here, all the details related to the header and footer are inherited from the base.twig file, which is the parent template, while the content block will be replaced with the post title and content. How much fun is that?

WordPress CheatSheet for Timber

The developers of Timber have made sure that it complements WordPress in every possible way from the core to the end users. Though the conversion syntax of WordPress functions in Timber is somewhat different, it’s pretty well documented. Towards the end of this article, I’ll share a list of some of the conversions for the WordPress functions and their Timber equivalents. Let’s recap.

Brief Recap!

In my previous article, I created a welcome message which populated simply via a PHP string on the homepage of my demo website. The code for this can be found in its branch on GitHub. Let’s repeat this procedure once again but with a different and more technical approach.

Right now, I’ll display the same welcome message but this time via creating a new page which populates on the homepage.  

Retrieving WordPress Functions in Twig

Create a new page with the title “Welcome to My Blog!” and add some content inside it before you hit the publish button.

adding a new page in twig

Now let’s display the contents of this welcome page on the homepage. To do so, once again go to the index.php file and add the following lines of code.

Here, I added a $context array, inside which I added an element welcome_page and then used the get_post() function to fetch the page which I just created. To do so, I submitted the page ID, which is 4 in this case.

Inside the welcome.twig file, let’s print_r the element welcome_page and see what data we get. My welcome.twig file looks like this at the moment.

I can confirm that this element in the $context array now has a TimberPost object for that particular page with ID 4.

TimberPost object

From here, we can get all the properties which can be displayed on the front-end. For example, I want to display the page title and content only. So now my welcome.twig file looks like this:

And the homepage has the info we need.

Welcome Homepage

WordPress Cheatsheet

As I said earlier, Timber provides you with some handy conversions of the WordPress functions. These functions can help you get information related to the:

  • Blog
  • Body Classes
  • Header/Footer

get_context() function

There is a Timber::get_context() function which retrieves loads of site information which a developer would want to display on the front-end across the site. The documentation explains it like this:

This is going to return an object with a lot of the common things we need across the site. Things like your nav, wp_head and wp_footer you’ll want to start with each time (even if you over-write them later). You can do a $context = Timber::get_context(); print_r( $context ); to see what’s inside or open-up timber.php to inspect for yourself.

Not only this but you can add your own custom data to this function via a handy filter.

Below you can find a few more conversions like this one, which can be used with Timber.

Blog Info

  • blog_info('charset') =>  site.charset
  • blog_info('description') =>  site.description
  • blog_info('sitename') =>  site.name
  • blog_info('url') =>  site.url

Body Class

  • implode(' ', get_body_class()) => <body class=" body_class ">

Theme

  • get_template_directory_uri() =>  theme.link  ( for parent themes)
  • get_template_directory_uri() =>  theme.parent.link  (for child themes)
  • get_stylesheet_directory_uri() =>  theme.link
  • get_template_directory() =>  theme.parent.path
  • get_stylesheet_directory() =>  theme.path

wp_functions

  • wp_head() =>  wp_head
  • wp_footer() =>  wp_footer

Let’s experiment with a few functions, starting off with the blog info. In place of foo, write site.name

The front-end will display the site title like this:

sitetitle function in Timber

Timber also has some function conversions to display the posts and post-related information via TimberPost(). Before I explain the usage of this function, let’s list the function conversions related to it.

Post

  • the_content() =>  post.content
  • the_permalink() =>  post.permalink
  • the_title() =>  post.title
  • get_the_tags() =>  post.tags

Usage

Use this code in the single.php file.

Now let’s test the  post.title function inside our Twig file.

Save it and the front-end will display the post title like this:

posttitle function in Timber

Your Turn!

Today, you witnessed the practical implementation of the DRY principle with Timber and Twig while building a WordPress theme. Go through this tutorial and try to implement it, and let me know about any questions you might have. You can find the complete code in the WP Cheatsheet branch over in this GitHub repository.

In the next and the last article, I will discuss how to handle images and menus in a Twig-based WordPress template. Till then, reach out to me on Twitter to get your questions answered, or post one here.