Craft CMS is our content management system of choice and has been for quite some time now. As a Web Developer, I can tell you that it is an absolute beauty to work with. At the heart of Craft CMS lies Twig, a popular templating engine that makes building dynamic websites a breeze.
Twig provides a user-friendly way to translate the data that is set in Craft’s control panel into HTML, which can be viewed by the user. With Twig, you can easily manipulate data, generate HTML, and create reusable components. 💡
Craft CMS leverages Twig as its default templating language because of its simplicity, security, and performance. Whether you're a beginner or an experienced developer, understanding Twig will give you the power to get up and running with Craft CMS.
Let's dive in and explore the basics of Twig! 💪
Jason coding in the studio
Twig uses double curly braces {{ }} to denote variables and expressions. These placeholders can be used to output dynamic content on your website. For example, if you want to display the title of an entry, you can use the following code:
<h1>{{ entry.title }}</h1>
In addition to variables, Twig supports control structures such as conditionals and loops. You can use if statements, for loops, and other logic to customize the display of your content based on specific conditions. Here's an example of an if statement in Twig:
{% if entry.author %}
<p>Written by: {{ entry.author }}</p>
{% endif %}
If you want to loop through some entries that you have created in the control panel, it’s as easy as:
{% for entry in craft.entries %}
<p>{{ entry.title }}</p>
{% endfor %}
You can also loop through a basic array of data using the same for loop structure
{% for colour in ['red', 'green', 'blue'] %}
This colour is {{ colour }}
{% endfor %}
To make things a little tidier and ‘DRY-er’ (Don’t repeat yourself!) we can also set variables like so:
{% set colours = ['red', 'green', 'blue'] %}
Twig also provides filters and functions that allow you to modify and manipulate data. You can apply filters to variables to transform their output. For instance, you can capitalize a string using the capitalize filter:
<p>Today is {{ now | date }}</p>
To make sure you don’t forget what some parts of your code are doing, you can leave comments in Twig using the following:
{# Hey there, his is a comment! #}
Even with these basics, there's enough for you to really get going with Twig and start to bring in some dynamic functionality to your Craft CMS website.
Once you’ve got your head around the basic syntax of Twig, you can start to explore some more advanced techniques. Take a look at the following examples:
Twig allows you to create reusable templates and extend them to build consistent layouts across your website. You can define a base template and then extend it in other templates using the extends keyword.
{# -- Template '/_layout/base.twig' -- #}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="{{ currentSite.language }}">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>
{{ title ?? siteName }}
</title>
</head>
<body>
{% block body %}
{% endblock %}
</body>
</html>
{# -- Template '/_pages/general.twig' -- #}
{% extends "_layouts/base.twig" %}
{% set title = 'My new page' %}
{% block body %}
<h1>
This is my fancy new Craft CMS website.
</h1>
{% endblock %}
With Twig's include statement, you can break your templates into smaller, manageable chunks and include them wherever needed. This promotes code reusability and keeps your templates organised. A prime example of this is for creating product thumbnails.
{# -- Template '/_components/cards/product.twig' -- #}
{% set product = product ?? null %}
{% if product %}
<a href="{{ product.url }}" class="product">
{% if product.image|length %}
<img src="{{ product.image.one().url }}" class="product__image">
{% endif %}
<div class="product__title">
{{ product.title }}
</div>
<div class="product__price">
{{ product.price|commerceCurrency() }}
</div>
</a>
{% endif %}
{# -- Template '/products/index.twig' -- #}
{% for product in craft.products %}
{% include '_components/cards/product' with {
product: product
} %}
{% endfor %}
Twig's macro functions let you define reusable snippets of code. You can create macros for common tasks and call them wherever necessary, reducing code duplication and improving maintainability.
{% macro navItem(label, path) %}
<li class="nav-item"><a href="{{ url(path) }}">{{ label }}</a></li>
{% endmacro %}
<nav class="global-nav">
<ul>
{{ _self.navItem('About', 'about') }}
{{ _self.navItem('Blog', 'blog') }}
{{ _self.navItem('Contact', 'contact') }}
</ul>
</nav>
{# -- Template '/_components/drawer.twig' -- #}
{% set heading = heading ?? null %}
<div class="drawer">
<div class="drawer__overlay">
</div>
<div class="drawer__content">
{% block drawerContent %}
{% endblock %}
</div>
</div>
{# -- Template '/_layouts/global.twig' -- #}
{% embed '_components/drawer' with {
heading: 'My Basket'
} %}
{% block drawerContent %}
{% for lineItem in craft.commerce.lineItems %}
{% include '_components/cards/product.twig' with {
product: lineItem.purchasable.product
} %}
{% endfor %}
{% endblock %}
{% endembed %}
By harnessing these advanced Twig techniques, you can create modular, maintainable, and scalable Craft CMS templates.
In conclusion, Twig is a fantastic tool that allows developers to create beautiful and dynamic websites in Craft CMS right alongside HTML, CSS and JS. What we’ve covered in this article really is just the basics of what you can do with Twig in your Craft CMS projects.
So, go ahead, give Twig a try, I dare you.
Happy coding! 🎉✨
We love Craft CMS at MadeByShape in Manchester
I'm Tom, a Web Developer at Shape - when I'm not making slick Craft CMS websites, I'm usually eating Peanut Butter or riding my bike.