Twig Templating Tips and Tricks for Craft CMS

Craft CMS templating got you twigging out? Read this!

Twiggin' Out

Craft CMS is a powerful content management system that offers a flexible templating system using Twig, a popular PHP-based template engine. Twig provides a variety of features and functions that allow developers and designers to create dynamic and complex templates with ease. Whether you're a seasoned Craft CMS user or just getting started, mastering Twig can make your templating workflow more efficient and productive. In this blog post, we'll share some handy Twig tips and tricks that will help you get the most out of Craft CMS templating. From conditional statements to loop iterations, we'll cover several techniques that will take your Craft CMS templates to the next level.

Use the 'include' Tag to Modularize Your Templates

One of the most powerful features of Twig is the include tag, which allows you to include reusable pieces of code in your templates. This can be especially useful for creating modular layouts or repeating elements on multiple pages.

Here's an example of how you might use the include tag in a Craft CMS template:

{% include '_partials/header.twig' %}

  {% block content %}
    {% include '_partials/intro.twig' %}
    {% include '_partials/featured.twig' %}
  {% endblock %}

{% include '_partials/footer.twig' %}

In this example, we've included four partial templates: header.twig, intro.twig, featured.twig, and footer.twig. The header.twig and footer.twig templates are included in every page of the site, while the intro.twig and featured.twig templates are included only on pages that define content blocks for those sections.

By modularizing your templates in this way, you can keep your code organized and easily updateable. If you need to make a change to a particular section of your site, you can simply update the relevant partial template without having to modify every page that includes it. This can save you a lot of time and effort in the long run, especially as your site grows and evolves over time.

Use Twig's Built-in Filters to Manipulate and Format Your Data

Twig provides a wide range of built-in filters that can be used to manipulate and format your data. These filters can save you time and effort by reducing the amount of code you need to write to achieve common formatting tasks.

Here are some examples of filters you might use in a Craft CMS template:

{{ "hello, world"|upper }}


{{ 1234.56|currency('USD') }}


{{ "Lorem ipsum dolor sit amet"|truncate(10) }}


{{ "The quick brown fox"|replace('quick', 'slow') }}


{{ entry.postDate|date('F j, Y') }}

In this example, we've used several Twig filters to manipulate and format our data. The upper filter converts a string to uppercase, while the currency filter formats a number as currency. The truncate filter truncates a string to a certain length, while the replace filter replaces one string with another.

We've also used the date filter to format a date. In this case, we're formatting the postDate field of an entry using the F j, Y format, which will output the date in a format like "January 1, 2023".

Use Conditional Statements to Control Your Output

Twig's if statement allows you to conditionally output content based on certain criteria. This can be useful for showing or hiding elements based on user input, checking for the presence of certain data, or creating dynamic layouts.

Here's an example of how you might use the if statement in a Craft CMS template:

{% if entry.title %}
  <h1>{{ entry.title }}</h1>
{% endif %}

{% if entry.body %}
  <div class="entry-body">{{ entry.body }}</div>
{% endif %}

{% if currentUser %}
  <p>Welcome, {{ currentUser.friendlyName }}!</p>
{% endif %}

In this example, we're using the if statement to conditionally output three different elements. The first if statement checks whether the entry.title field is set, and if so, outputs an <h1> tag with the title. The second if statement checks whether the entry.body field is set, and if so, outputs a <div> tag with the body content. The third if statement checks whether there is a logged-in user and if so, outputs a welcome message with the user's friendly name.

By using conditional statements like these, you can create dynamic and responsive templates that adapt to the content and context of each page. Whether you're showing or hiding elements based on user input, checking for the presence of certain data, or creating complex layouts, the if statement is a powerful tool that can help you achieve your goals with minimal code.

Use For Loops

Twig's for loop makes it easy to iterate over arrays and output dynamic content. This can be especially useful for creating lists or grids of content, or for generating complex navigation menus.

Here's an example of how you might use the for loop in a Craft CMS template:

{% for entry in entries %}
  
    <h2>{{ entry.title }}</h2>
    <div class="entry-body">{{ entry.body }}</div>
  
{% endfor %}

In this example, we're using the for loop to iterate over an array of entries and output an <article> tag for each one. Within the loop, we're accessing the title and body fields of each entry using the entry.title and entry.body syntax.

Here's another example that shows how you might use the for loop to generate a navigation menu:

<ul><li>
    {% for item in navigation %}
      </li><li><a href="%7B%7B%20item.url%20%7D%7D">{{ item.title }}</a>
    {% endfor %}
  </li></ul>

In this example, we're using the for loop to iterate over an array of navigation items and generate a list of links. Within the loop, we're accessing the url and title fields of each navigation item using the item.url and item.title syntax.

Inheritance!

Twig's inheritance and block system allows you to create modular templates with a consistent structure and layout. By defining blocks in your base template and overriding them in your child templates, you can create a flexible and scalable system for building out your website's structure and content.

Here's an example of how you might use inheritance and blocks in a Craft CMS template:

Base Template (_layouts/base.twig):

{% block content %}
    
      <h1>{% block heading %}Default Heading{% endblock %}</h1>
      {% block intro %}{% endblock %}
    
  {% endblock %}
  
  {% block extra_footer %}{% endblock %}

Child Template (_pages/home.twig):

{% extends '_layouts/base.twig' %}

{% block title %}Homepage{% endblock %}

{% block heading %}Welcome to My Website{% endblock %}

{% block intro %}
  <p>This is the homepage of my website.</p>
{% endblock %}

In the code above, we're using inheritance and blocks to create a base template (_layouts/base.twig) and a child template (_pages/home.twig). The base template defines a basic HTML structure, including a title tag, a link to a stylesheet, and a basic layout for the content. Within the base template, we've defined several blocks (title, extra_head, content, heading, intro, extra_footer) that can be overridden in child templates.

The child template (_pages/home.twig) extends the base template using the extends tag, and overrides several blocks to provide specific content for the homepage. Within the child template, we've overridden the title block to set the title of the page to "Homepage", the heading block to display a specific heading for the page, and the intro block to display a specific introduction for the page.

By using inheritance and blocks in this way, you can create a flexible and scalable system for building out your website's structure and content. You can define common elements in the base template and override them in child templates to create custom pages with a consistent layout and structure. This can save you a lot of time and effort, especially as your site grows and evolves over time.

Don't stop there!

By incorporating these five tips and tricks into your Craft CMS templating workflow, you can create dynamic, modular, and responsive templates that adapt to the content and context of each page. Whether you're using Twig's include tag to modularize your templates, taking advantage of its built-in filters to manipulate and format your data, or using its if statement to control your output, Twig provides a wide range of features and functions that can make your templating workflow more efficient and productive.

If you want to learn more about Twig and its capabilities, be sure to check out the official Twig documentation. With its comprehensive documentation and extensive community support, Twig is a powerful and flexible tool that can help you achieve your templating goals with minimal code.

Continue reading.

Extending Craft's Element API with Custom Serializers

The Element API plugin is a very powerful tool that you can use for quickly exposing your data structures to an external source.

Find out more
Why We Love Craft CMS

Here at Brilliance, we LOVE CraftCMS. Our clients love it as well.

Find out more
Ethereum Development Community Nears Merge Date for Proof of Stake

A brief introduction to consensus mechanisms and why proof of stake is the right move for Ethereum.

Find out more
See all posts

Let's chat about your project

6118 SE Belmont St Ste 404
Portland, OR 97215

This site is protected by reCaptcha and its Privacy Policy and Terms of Service apply.

Contact image