Twig Templates in Craft by Ryan Irelan

The how, what, and why of using Twig in Craft templates. A companioln to the Learning Craft course.

In this course you will get a comprehensive overview of working with Twig templates in Craft. The goal is to get over the hump of writing Twig code, dispel any myth that using Twig is difficult, and help you take the next step in using Craft. Twig Templates in Craft by %author From a course at Mijingo.com Introduction

Welcome to Twig Templating in Craft. In this course we will cover how to create templates with Craft using Twig, the built-in template engine.

Our goal in this course is to dispel the myth that working with Twig in Craft is difficult or confusing. I’ve found that a big questions people new to Craft have are:

Where does Twig end and Craft begin? Which tags are Craft and which are Twig? Where should I look when I need help? The Craft documentation or the Twig documentation?

By understanding what’s Craft and what’s Twig we’ll be able to answer all three of those questions.

We will work together to review the basics of templates in Craft first, and the move into the basics of Twig, and, finally, into the Craft-specific implementation of Twig.

What’s Craft?

If you’re watching this video, I assume you already know what Craft is. But just in case…

Craft(http://buildwithcraft.com) is a modern content management and publishing system by Pixel & Tonic(http://pixelandtonic.com). The CMS is built on PHP, using the Yii framework. It, as you can guess, uses the Twig template engine for the template piece of the CMS.

What We’ll Cover

This course is broken up into three different modules:

Introduction to Craft Templates & Twig Craft + Twig Craft Navigation & Pagination

The first module will get us acquainted with Craft templating and how vanilla Twig (not as part of Craft) works.

The second module–the longest part of the course–will clarify how Craft and Twig work together, so you can jump right in to building your first Craft website (or getting better at building your second, third, or fourth site).

Copyright %Y Mijingo, LLC - %URL 2 Twig Templates in Craft by %author From a course at Mijingo.com

The third module covers how to use Craft navigation and pagination tags.

Pre-requisites

To use this course, you ideally have already watched my Up and Running with Craft video course(https://mijingo.com/products/screencasts/craft-cms-tutorial/) or have worked with Craft enough to understand generally how it works. This course won’t teach you how to build a site in Craft–we will only be focused on the templates. If you want to learn the steps to building a site in Craft, you should watch my Learning Craft course.

A general familiarity with HTML and how to navigate an HTML document would be helpful for this course. Although, if you are already doing web development with other content management systems or building static templates with HTML and CSS, then you should have no problem following along in this course.

There is absolutely no programming experience required. While we will look at some programming concepts that come with Twig and Craft, this course doesn’t require that you have programming experience (whether a formal education or even work on building web publications with languages like PHP Ruby or Python). This course is set up to be for people who do not have programming experience and simply want to build a website using the craft CMS.

You should also have a local development environment set up already that you can use to build the Craft website for this course.

If you need more information on how to set up localhosting, check out my Reliable Localhosting course(https://mijingo.com/products/screencasts/setting-up-a-local-web-server/) to learn more.

Installing Craft

Later on we will install the Happy Lager sample site. If you haven’t installed Craft before you can follow my video tutorial on it: https://mijingo.com/lessons/installing-craft-cms/

Other we will cover installing the site in the Installing the Sample Site section later in this course book.

Craft Licensing

A question you might have is:

Do I need a craft license in order to follow along with this course?

Copyright %Y Mijingo, LLC - %URL 3 Twig Templates in Craft by %author From a course at Mijingo.com

No, you do not need a Craft license to follow along with this course. However, you do want to make sure that you run the local version of the site at happylager.dev so that you can run Craft without restrictions. Craft is set up in such a way that using certain localhosting domains allows you to run a full version of Craft without needing a license.

This is great for getting started but you should definitely pick up a Craft license for your next project!

Copyright %Y Mijingo, LLC - %URL 4 Twig Templates in Craft by %author From a course at Mijingo.com Module 1: Basics of Templating in Craft

Goal: Get comfortable and familiar with general template setup in Craft.

Before we start looking into how Craft and Twig work together, let’s first review how Craft works with templates.

How Craft Stores Templates

Craft templates are stored as normal HTML files. However, in addition to the HTML, Craft templates also have a special type of code (this is the Twig code we’ll cover later) that tells Craft where to insert content that is stored in the database.

(If you have used other content management systems like ExpressionEngine or WordPress, then you’re familiar with how this works.)

In Craft, the templates are not accessible via the control panel. Templates are stored solely as files. They are not stored in the database and people who have access to the Craft control panel can not access the templates or edit them.

Speaking of storing templates as files, there are some really nice features to how Craft lets you store and name templates and template directeories.

Simply put: Craft doesn’t care what you name your templates, what you name your template directories or how you organize your templates and template directories.

The only thing Craft cares is that you tell it where those templates are when you specify a template that is assigned to a section. show example of a template directory and templates

The template directory structure and naming are completely up to you: you just need to tell Craft where to find the templates.

To do this, when you set up a section in craft, you specify a template that craft should use when craft needs to display an individual entry for that section. For example, let’s say we have a blog on a website. When we set up that blog section in Craft, we tell Craft that when somebody wants to view an individual entry of that blog, then they need to use blog/view.

Copyright %Y Mijingo, LLC - %URL 5 Twig Templates in Craft by %author From a course at Mijingo.com

Craft Routing to Templates

Craft has a routing check sequence that every request goes through so it ends up at the right place, delivering the right page.

The second-to-last check in the sequence to see if the request URI matches a template. If the URI is a valid template path (directory + template), then Craft will render that template.

If you have a request for mysite.com/offices/austin template offices/austin.html and Craft goes through its checks and doesn’t find a match before it gets to the template check then it will render the offices/austin.html template. If you had an entry with that URI then it would render the entry instead (using whichever section entry template you specified).

At the end of the check sequence, if there are no matches, Craft will return a 404 error. If you don’t have a custom 404 template, Craft will render the default view. To create a custom 404 template, add a 404.html template file in the root of your craft/templates directory and Craft will use it.

Dynamic Routes

There are times when you want to load a specific template but not at the URI that is a literal mapping of the template directory and template file name.

In Craft this is done with Dynamic Routes. These routes are specified in the Control Panel and can map a URI to a template. This is handy for when you want to pass along other information in URI, like dates.

A good example given in the Craft documentation is for an archive page. You want to pass create a news archive page for a year and month. Your URI is: news/year/month but your template is news/_archive .

You can use Dynamic Routes in Craft to map news/2015/02 to news/_archive and then use the two last segments of the URL to determine which content to show.

Introduction to Twig

Copyright %Y Mijingo, LLC - %URL 6 Twig Templates in Craft by %author From a course at Mijingo.com

Twig is a template engine for PHP applications. It takes a series of tags and compiles them into standard PHP that is then processed by PHP on your web server. It’s used by the development framework , the e-commerce platform Lemonstand, 8, and is similar to , the templating engine.

Twig is not a CMS or application that stores or handles your website data.

Twig is also customizable and extensible. With Twig, developers can specify custom tags and filters that add functionality beyond the tags that come with it. You’ll see later on how this is implemented in Craft.

Twig can also do some programmatic things, like match, logic, and assigning variables.

Overview of Twig Syntax

Twig’s template engine syntax is approachable and simple–much more approachable than standard PHP.

Instead of outputting data using a typical PHP variable, like this:

Twig uses a more approachable syntax consisting of two curly braces:

{{ body }}

The reduction in characters used–and the number of different characters–makes for a cleaner look of the template. A cleaner looking template is easier to write, read, and debug.

Twig aims to give all of the power of PHP but without writing PHP. You do can more in Twig than just output variable contents. You can also do programmatic things, like logic and control structures.

In PHP, you’d typically loop through an array of data using a for -loop:

Copyright %Y Mijingo, LLC - %URL 7 Twig Templates in Craft by %author From a course at Mijingo.com echo $entry‘body’; } ?> to output some data stored in the array. In this case, it’s the entries of a news blog.

In Twig, we’d do something like this:

% for entry in entries % { entry.body } % endfor %

Twig also handles logic like if statements:

% if entries|length == 0 %

No entries available

% endif %

All of this you can do in PHP but Twig makes the syntax simpler, including passing variables through filters to manipulate or check them.

The example above where we checked the length. That uses a Twig filter called length that returns the numbers of items in an array or the length of a string.

Twig comes with a couple dozen filters built-in(http://twig.sensiolabs.org/doc/filters/index.html) and you can create custom filters, too. In the case of Craft, there are custom filters available.

Here’s another example of a filter:

( post.title|upper }

This takes the post title and makes it uppercase.

Twig also allows you to set variables in your template. In PHP, we’d do:

And in Twig, we’d do:

% set author = ‘Ryan Irelan’ %

Copyright %Y Mijingo, LLC - %URL 8 Twig Templates in Craft by %author From a course at Mijingo.com

Okay by now you’re probably wondering about the difference in the curly braces I’m using. Some examples use double curly braces and some examples use a curly brace and a percent sign.

These are called delimiters and Twig has three types.

Output Tags

The code with the double curly braces are output tags. They print variable contents to the screen (i.e. output content in your template).

{ author }

The author variable would output my name (because we set it in the previous example).

But output tags can generate the output on the fly and then print it to the screen. How about a little math?

{ 4 * 4 }

This output tag will do the multiplication of 4 and 26 and print out the product. I’m unsure how practical it is to do math like this in the template but there you have it.

If you want to use an output tag to pass in data to another tag, like when we set a variable in Twig, then you don’t need to use the double curly braces.

% set result = 4 * 4 %

If we printed out the value of the result variable we just set than it would render:

16

The Twig documentation(http://twig.sensiolabs.org/doc/templates.html#variables) calls out that the curly braces are not part of the variable itself but instead an indicator that the value of the variable contained within should printed to the screen.

Statement/Logic Tags

With the same author variable, if I did:

% author %

Copyright %Y Mijingo, LLC - %URL 9 Twig Templates in Craft by %author From a course at Mijingo.com it would print out nothing because that is not the syntax of an output tag. It’s a statement tag that executes code (like our for loop).

Statement or logic tags use the curly brace plus percent sign delimiter. Earlier we set the value of the author variable to my name. To do that we had to use the statement tag syntax with the set tag:

% set author = ‘Ryan Irelan’ %

But logic tags in Twig and Craft can come in multiple forms.

Some are just a single tag, like this tag:

% requireLogin % which you would put at the top of a template in Craft to require a logged-in state. If a visitor is not logged in than Craft will automatically redirect them to the log-in page. This is a special tag provided by Craft and isn’t a standard Twig tag.

Other logic tags take parameters, like the redirect tag in Craft:

% redirect “tos” %

The redirect tag takes one parameter, which is the URL or path to where you want to redirect the visitor. This is a tag specific to Craft but there are some Twig tags you should know, too.

Another type of tag is one that has an opening and closing tag, like the for tag in Craft. We looked at this earlier one when reviewing the Twig syntax.

% for % % endfor %

The tag pairs have an opening tag and a closing tag. The closing tag will typically have an “end” prefix, like endfor , endpaginate , and endblock .

Even the set tag we used earlier to set a variapble can be used as a tag pair. This allow you to set a block of text to a variable.

% set socialLinks %

% endset %

Another example of a tag pair–and by far your most used tag while writing Twig template code for Craft–is the for -loop. It’s how you will loop through and display section entries in your templates and output other lists, like categories.

Here’s the same example from earlier. This is a for -loop to display content from an array of blog posts:

% for entry in entries % { entry.body } % endfor %

It uses the curly brace plus percent sign delimiter for both the opening and closing tags of the for - loop. This delimiter tells Twig that what’s between needs to be executed as a statement (in this case a for -loop).

You should definitely become familiar with the syntax of a basic Twig for loop before jumping into Craft. We’ll cover the Craft implementation of Twig later in this course.

Comment Tags

This one is straight-forward but perfect for adding comments to your templates but not have those comments render like HTML comments would.

# Begin logic for sidebar #

Using a single opening curly brace paired with a pound sign, we can create the un-rendered comments. They’ll always be available in your template file but never rendered by Twig.

Any code that is inside the comment tag will not be executed by Twig.

# removing this for now to debug % for entry in entries % { entry.body } % endfor %

Copyright %Y Mijingo, LLC - %URL 11 Twig Templates in Craft by %author From a course at Mijingo.com }

More Information on Twig

If you want to explore Twig itself a little deeper, you can peruse the documentation(http://twig.sensiolabs.org/doc/templates.html) available from SensioLabs, the creators of Twig.

The documentation describes vanilla Twig and doesn’t include any Craft-specific implementations, tags, filters, or functions. However, the Twig for Template Designers(http://twig.sensiolabs.org/doc/templates.html) resource is worthy of a bookmark, in case you ever need to verify how to format a Twig statement or other bit of code.

Twig in Your Code Editor

It’s always handy to have language snippets and proper syntax highlighting available in our code editors. Twig IDE support is widely available(http://twig.sensiolabs.org/doc/templates.html#ides- integration). You find plugins and bundles for Textmate, , , , Coda, Notepad

Copyright %Y Mijingo, LLC - %URL 12 Twig Templates in Craft by %author From a course at Mijingo.com Module 2: Coding in Craft with Twig

Introduction text

What We’re Building

In this course we are going to work with the Happy Lager website. This is a demo site provided by Pixel & Tonic, the makers of Craft.

Happy Lager is a website for a fictional digital agency that produces mobile apps, design, and web development.

The site is made up of a handful of main sections: news, services, and work. The sections and templates make up a site that shows the work of this fictional company, and some news.

We’re going to start with an incomplete version of the site and then work from there, building a few templates as we learn more about Craft templating with Twig.

You should download the Mijingo fork of this site, starting with the tag mijingo-twig-craft-begin . You can also download the tag mijingo-twig-craft-end to see the completed site.

We will mostly focus on the homepage, the news section, and some included templates for navigation and pagination. We won’t work in the control panel because this course is template-focused. We will work from the assumption that you have a Craft installation installed and populated with the fields and data needed to output content to the templates.

If you are unfamiliar with how to use Craft and set up a website, my course Learning Craft(https://mijingo.com/products/screencasts/craft-cms-tutorial/). It’s a 2 ½ hour journey through building a basic website with the CMS.

Installing the Sample Site

Before we cab get started writing Craft and Twig code, we need to first download and install the Happy Lager sample site.

1. Download the starting tag for the Mijingo fork of the Happy Lager site. You can get the code here: https://github.com/Mijingo/HappyLager/releases 2. Set permissions for the happylager/craft/storage directory to 777 so Craft can write to it

Copyright %Y Mijingo, LLC - %URL 13 Twig Templates in Craft by %author From a course at Mijingo.com

3. Set permissions to happylager/craft/config to 744,774, or 777 (depending, see docs for more information) 4. Download the latest version of Craft from buildwithcraft.com so you can get the craft/app directory. 5. Copy the just-downloaded craft/app directory to happylager/craft 6. Create a new MySQL database called happylager 7. Import happylager.sql into the database (this database file is available from the tag zip file you downloaded from Github). 8. Set up your localhosting environment to have the hostname happylager.dev point to the happyloager/public directory on your computer. If you don’t know how to do this, review my free course Reliable Localhosting(https://mijingo.com/products/screencasts/setting-up-a-local- web-server/). 9. Point your web browser to happylager.dev/admin and Craft may finish up some updates before presenting you with a login screen. 10. Log in with username: admin password: password

With the sample site installed, let’s move on to learning how Twig and Craft work together to make template creation fun!

Overview of Twig in Craft

Up until this point we’ve talked about Craft templates and we’ve reviewed Twig. But how do they work together? More importantly–and a question that is often confusing–where does Twig end and Craft begin?

Let’s look at some pure Twig code again.

% for entry in entries % { entry.body } % endfor %

This for -loop iterates through all posts in the entries array and prints out the body content. Twig is the mechanism that is doing the looping but the it isn’t in charge of where the data in entries comes from. It just handles the logic of what to show when and outputting that to the web page.

You can think of Twig as the machine that processes the data that is passed to it. It doesn’t care what that data is. It could be a manually-set array just two lines of code above or something that is retrieved from a database.

Copyright %Y Mijingo, LLC - %URL 14 Twig Templates in Craft by %author From a course at Mijingo.com

Craft, on the other hand, supplies the data. We pass the Craft data to the Twig tags and Twig assists us in outputting it to the template.

% for entry in CRAFT_DATA % { entry.CRAFT_DATA } % endfor %

I clearly marked where Craft data is being used with CRAFT_DATA . Everything else is Twig code.

Using real Craft Twig code, that same block of code would look like this when we iterate over sections entries in order to output them on the page.

% for entry in craft.entries.section(‘blog’) % { entry.title } % endfor %

Whoa, hang on. What’s this big thing connected by dots?

Let’s start with the leftmost part and the word craft . This is a global variable in Twig and it allows Twig to request and Craft to hand over to Twig some data to use to output content to pages via Twig templates.

The entries –connected by a dot–is a property of the craft global variable that tells Craft what type of data we want to return (in this case entries from a section). The section property tells Craft that we want to pass Twig content from a specific section. We specify the section by passing a section name as an argument. This is the ('blog') that comes after section .

This code tells Twig to take the Craft data we pass in via the craft global variable that is made available for us from Craft and get the entries for the blog section.

We can append another property to that to specify a limit:

% for entry in craft.entries.section(‘blog’).limit(‘25’) % { entry.title } % endfor %

We add the limit property and then pass in a value. In this case we want to limit the number of entries Twig displays to 25. Craft retrieves the data we requested and hands that back to Twig, which then iterates over it and displays it based on the variables we specify by field name.

Copyright %Y Mijingo, LLC - %URL 15 Twig Templates in Craft by %author From a course at Mijingo.com

So, to reiterate:

% for entry in CRAFT_DATA % { entry.CRAFT_DATA } % endfor %

Everything that isn’t marked as CRAFT_DATA is Twig.

If we think about Twig and Craft data as separate then it’ll make it easier for us to compose our Twig code and pull in the Craft data.

But Twig can do some things on its own, too, without any outside data. Here’s a dropdown for an age select.

Without any Craft data, this will output a dropdown with the ages 1 to 100. It uses the Twig .. operator which is a shorthand way of using the range function.

Here’s the same code but using the range function instead of shorthand:

Where’s the line?

In Craft, the line between Twig and Craft is that Craft is the data that Twig uses to process and output and Twig is the language that makes it easy to write templates and display that Craft data.

Craft: data. Twig: language.

Copyright %Y Mijingo, LLC - %URL 16 Twig Templates in Craft by %author From a course at Mijingo.com

The Twig documentation isn’t Craft-specific, so it may take a little translation to understand how the code examples apply to Craft. Similarly, the Craft documentation only covers certain, high-level aspects of Twig; it’s not a comprehensive resource.

By understanding the line between Craft and Twig, we will know how the template code works and where to look when we need help.

Building Templates (Hands-on)

Let’s jump in and work with some code to put into practice the theory we’ve already learned about Craft and Twig template code.

Coding the Templates

For this course we’ll look at the News section of the Happy Lager site. To follow along you’ll need to download, open, and install the version of the Happy Lager website that’s in the starting tag download.

The index template for the News section has a bunch of markup already in it but it’s all static. We need to build this out and make it dynamic using Craft and Twig tags. Along the way we’ll learn even more about them.

Let’s start with the list of entries of news articles. We’ll skip over the featured news entry right now and start right below it, where there are a handful of news-entry divs.

We need to populate these tags with data from Craft and we’ll do that using a for -loop.

The for -loop

We looked at the for -loop earlier but let’s now put it into practice.

The for -loop, like it does in other languages, allows you to iterate or loop over a sequence of some type (typically an array) and output some data.

Here’s the basic syntax:

% for entry in entries % { entry.title } % endfor %

Copyright %Y Mijingo, LLC - %URL 17 Twig Templates in Craft by %author From a course at Mijingo.com

The for -loop in Twig starts with for and ends with endfor , both of which are encased in single curly braces with a percent sign. In between we can output data from the loop.

Let’s implement the for -loop to output the latest 4 entries from the News section. We’ll start right below the featured entry and come back around in a few minutes to add that.

First we need to remove all but one of the article elements because the Twig for -loop will iterate over that article element and create as many as needed.

Then we can add the loop so it looks like this:

% for newsEntry in craft.entries.section(‘news’) %

<figure>

{ newsEntry.title }

Et harum quidem rerum facilis. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo mus quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut.

|Read More

% endfor %

We’re using the for -loop to iterate over the data returned when we use craft.entries for the news section.

This Twig code loops once for each entry that is returned in craft.entries.section('news') and outputs all of the markup, in addition to replacing the Twig variables with the data in that loop.

Copyright %Y Mijingo, LLC - %URL 18 Twig Templates in Craft by %author From a course at Mijingo.com

This will be, by far, your most-used code while working with Twig and Craft. Outputting entries from sections is a core part of building websites with Craft; if you’re not already, you’ll soon be a master of building for -loops that loop over Craft section entries.

Conditionals

One area of the News landing page that we skipped over is the larger, featured news article that sits above the list we just brought to live using Craft Twig code. Let’s address that one now.

The featured item is simply the first news article returned–the most recent one posted–and it has a larger image set to the left of the title, author, description, and a link to read the entire news article.

In order to treat this news article differently, we’ll need to use a conditional to check for the first entry returned and then treat it with some special markup.

A conditional in Craft allows to control flow in the template. We use the if tag in Twig to make this happen. We can check if an expression evaluates to true:

% if loop.first % % endif %

In this example we’re testing if the loop.first expression is true. loop.first is a special variable made available to us from Twig (not Craft) that evaluates true if it is the first iteration of the for -loop.

There are other variations of the special loop variable:

loop.index - count of the current iteration, starting at 1 loop.index0 - count of the current iteration, starting at 0 loop.revindex - the number of iterations left until the end, starting at 1 loop.revindex0 - the number of iterations left until the end, start at 0 loop.last - evaluates true if it is the last iteration of the loop loop.length - the total number of items

For our implementation we only need to use the loop.first version of the loop variable. We’ll test whether it is the first loop and, if it is, we’ll deploy some special markup for the featured news entry.

We’ll take this markup that’s there for the featured entry and grab a few things from it:

Copyright %Y Mijingo, LLC - %URL 19 Twig Templates in Craft by %author From a course at Mijingo.com

<figure>

DIVA! Becomes Famous

admin

At the 2014 Webby Awards, Patton Oswald said that DIVA! “has done for women in the music industry what the 19th amendment did for women 100 years ago.“ Signissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non.

Read More

So the entries loop markup now looks like this:

% for newsEntry in craft.entries.section(‘news’) %

<figure> % if loop.first % % else % % endif %

{ newsEntry.title }

Et harum quidem rerum facilis. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo mus quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut.

Copyright %Y Mijingo, LLC - %URL 20 Twig Templates in Craft by %author From a course at Mijingo.com

|Read More

% endfor %

Variables

Twig allows us to set variable in our templates so we can repeatedly output a value without calling another method. It also helps make our templates cleaner because a variable can be a shorthand way to reference a value.

There are a few different ways to create and assign values to variables, and they all use the set tag.

The simplest way is like this:

% set title = “About Happy Lager” % by defining the variable name using the set tag and then assigning a value (in this case a string).

This variable can now be used throughout the template using the double curly braces syntax:

{ title }

If we had multiple variables to set at once–perhaps some metadata for the page that we wanted to use in mulitple places–we can do that by separating both the variables names and their values by commas.

Here’s a simple example:

% set title, subtitle, description = ‘About Happy Lager’, ‘The history behind the company.’, ‘Learn more about the history of the this mobile design and development agency.’ %

Each of those variables would then be available in the template, using the double curly brace syntax:

% set title, subtitle, description = ‘About Happy Lager’, ‘The history behind the company.’, ‘Learn more about the history of this mobile design and development agency.’ %

Copyright %Y Mijingo, LLC - %URL 21 Twig Templates in Craft by %author From a course at Mijingo.com

{ title } { description }

{ title }

{ subtitle }

{ description }

One last way of setting variables in Twig also uses the set tag but instead of as a single tag, we use it as a tag pair. Using it as a tag pair allows us to capture a block of text or code and assign it to the variable. This is handy for assigning a chunk of markup and content to a variable.

% set description_formatted %

  • Like us Facebook
  • Follow us on Instagram