The Mijingo Blog

Latest news, updates, free tutorials, and more from Mijingo.

New Lesson: Creating a Contact Form in Craft

by Ryan Irelan

There’s a new free lesson available over in Lessons area that covers how to build a contact form in Craft.

In the lesson, we add the form to our Crafty Brewery sample site so customers can contact us with questions about our brew products and recipes.

We’ve been building the Crafty Brewery site over the course of several videos in the Learning Craft video course. If you want to learn more about Craft, I encourage you to check out that series of videos.

During this lesson, here’s what we’ll learn:

  • How to install and configure the Craft first party Contact Form plugin.
  • How to code the Contact form template
  • How to add a honeypot CAPTCHA to the form.

Watch the Free Lesson

Filters in Twig and Craft

by Ryan Irelan

Filters in Twig and Craft allow you to alter the contents of a variable.

This could be a variable you set right in the template or one that is part of the data output provided by Craft (like when retrieving and looping through section entries).

Filters are applied right in the output tag, like this:


{{ variable | filter }}

and separated using the pipe character.

Here’s an example where we want to title case the string that is assigned to the variable.


{% set page_title = "an important news story" %}
{{ page_title | title }}

When outputting the contents of the page_title variable, we are running it through the title filter in Twig. This filter adjusts the string to title case, so every word starts with a capital letter.

It will output:

An Important News Story

Another very practical filter that you might use frequently is trim. This filter strips out whitespace at the beginning and end of a string.


{% set page_title = " an important news story " %}
{{ page_title | trim }}

That will remove the whitespace at the beginning and end of the string.

You can also trim specific characters by specifying them in parentheses.


{{ page_title | trim('.') }}

The previous example outputs:

an important news story

which is missing the title casing we did before.

Let’s add in both filters together. We do that by chaining together them with pipes.


{{ page_title | trim | title }}

That outputs:

An Important News Story

Craft-specific Filters

Pixel & Tonic created some special filters just to use in Craft. These filters won’t be listed in the Twig documentation, and, similarly, the Craft documentation won’t list all of the Twig filters. This is a situation where you’l need to refer to two different sets of documentation.

Here are a couple Craft filters that I find interesting:

  • markdown - processes the string passed to it using the Markdown library.
  • group - allows you to group array items together based on a common property that you define. The Craft docs have a great example of sorting the entries returned from a Craft section by the year of the entry.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

Using Variables in Twig and Craft CMS

by Ryan Irelan

Twig allows us to set variables 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 multiple 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.' %}

<html>
 <head>
  <title>{{ title }}</title>
  <meta name="description" content="{{ description }}">
 </head>
 <body>
  <h1>{{ title }}</h1>
  <h2>{{ subtitle }}</h2>
  <p class="description">{{ description }}</p>
 </body>
</html>

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 %}
    <p class="description>Learn more about the history of this mobile design company.</p>
{% endset %}

And that is the basic usage of variables in Twig and Craft CMS.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

Where am I in the Twig Loop?

by Ryan Irelan

Twig offers special loop variables that makes it easy to know which iteration of the for-loop, for example, we are on. This allows us to do different styling, markup, or other condition-based things.

In Craft, we typically loop through our section entries like this:


{% for entry in craft.entries.section('news') %}
    {{ entry.title }} 
{% endfor %}

Twig loops through the Craft data and displays each entry retrieved from the News section.

To check if this is the first iteration of the loop, we can use a conditional and check against the loop.first variable from Twig.

A conditional in Craft allows us 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:


{% for entry in craft.entries.section('news') %}
    {% if loop.first %}
        First!
    {% endif %}
    {{ entry.title }} 
{% endfor %}

In this example we’re testing if the loop.first expression is true. loop.first is one of six special loop variables made available to us from Twig (not Craft). This evaluates true if it is the first iteration of the for-loop. Otherwise it will evaluate false.

We’re not just limited to the loop.first variable. We can check for the current count, how many iterations until we reach the end of the loop (very handy!), and more.

Here are the other variations of loop:

  • loop.index - This is the count of the current iteration, starting at 1. Handy if you’re used to starting at 1 for counts or need to output it for something like table rows.
  • loop.index0 - Add a 0 and you get the count of the current iteration, starting at 0, instead of at 1. This is a more traditional way of counting iterations and how you would want to use it for for-loops.
  • loop.revindex - How many loops until the end? This variable will output the number of iterations left, starting at 1. If you want to start at zero, use the next variable.
  • loop.revindex0 - The same as the previous variable but starting at 0 instead of 1.
  • loop.last - A good way of knowing that your loop is about to end. Maybe you want to close a HTML tag or do something else before the loop is over. loop.last evaluates true if it is the last iteration of the loop.
  • loop.length - How many items are in the loop? This variable will output the total number of items so you know the total number of loops that will happen.

With the loop variable variations, you should need to set up a counter while iterating over data sets in Twig. Even you if need to start at 0 or 1, loop has you covered.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

Creating an Age Drop-down with Twig range()

by Ryan Irelan

Even though Twig is just (just) a templating engine for PHP applications (like the super smooth Craft CMS), it can also do lots of “programmy” things on its own, too.

Let’s say I need to create a form that includes a Age drop-down select field. I could populate the form element with data from a database or maybe some fancy library.

Or I could just build it in Twig. No outside data, like Craft data, is needed. Just Twig. All by itself.

Enough chit-chat, here’s the code:


<select name="age">
{% for age in range(1, 100) %}
    <option value="{{ age }}">{{ age }}</option>
{% endfor %}
</select>

In this example we’re creating a select field element called age and outputting an option element with a bunch of ages. 1 to 100 to be precise.

We use the range function that comes with Twig. It’s really just a mirror of PHP’s range function. But we don’t have to write PHP!

The range function returns integers, in order, based on the range you specify.

range(1, 100)

The number to the left of the comma is the beginning of the range. The number to the right is the end of the range. Everything in between–and including–those numbers will be outputted.

When we iterate over a range with a for-loop, and include an option tag, we get a handy age menu.


{% for age in range(1, 100) %}
    <option value="{{ age }}">{{ age }}</option>
{% endfor %}

We use the age variable to create a value for each option element, which we could then store when that option is selected.

When rendered, it looks like this:

Try it out in a Craft template to see it in action.

We can also use a shorthand version of the range function with the .. operator (in the docs they call it “syntactic sugar” mmmm). It’s a simpler way of writing the same thing:


<select name="age">
{% for age in 1..100 %}
    <option value="{{ age }}">{{ age }}</option>
{% endfor %}
</select>

And that’s how you generate a data-filled age field with just Twig.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

Using Macros in Twig and Craft

by Ryan Irelan

Macros are the Twig version of functions. Just like you would write a function in PHP to do something and return something, you can use a Twig macro to generate some output.

Macros are used for generating often used markup that might vary slightly each time. You put your skeleton markup in the macro and use parameters passed in to alter that markup and then output it.

Building a Twig Macro

A macro looks like this:


{% macro macroName(parameter1, parameter2) %}

    {# contents of the macro here #}

{% endmacro %}

Let’s take a look at an example for a list of social networking links that we want to include in several places on a site, but with different variations.

We’ll generate the list using a macro, so we can control which social networks are included, and add a class name to the ul element.

The first thing we need to do is define the data that we want to pass in to the macro. We’ll do that with a hash (more on Twig hashes).

The hash contains the information about each social network that we want to include in the list. Each network has a name and a URL. We set the hash to the variable networks.


{% set networks = {
    twitter: { name: "Twitter", url: "http://twitter.com/mijingo" },
    facebook: { name: "Facebook", url: "http://facebook.com/mijingo" },
    instagram: { name: "Instagram", url: "http://instagram.com/mijingo" }
    }
%}

Now, let’s build the macro. It’ll be our little factory for creating social link lists.


{% macro socialList(networks, className) %}
    <ul {% if className %}class="{{ className }}"{% endif %}>
    {% for network in networks %}
        <li class="{{ network.name | lower }}"><a href="{{ network.url }}">{{ network.name }}</a></li>
    {% endfor %}
    </ul>
{% endmacro %}

Let’s step through this macro line by line to understand what it does.

We’ll call the macro socialList. It takes two parameters; the first one is a hash of the networks we want to include, and the second one is the class name for the ul element.

The markup inside of the macro is an unordered list that outputs the list of social networks.

The class name is optional, and we add a conditional to only output a class name if one is passed in.

We use a for-loop to iterate over the hash passed in to the macro and then output a li element with the social network information for each social network.

In case we want to add additional styling or an icon, we populate the li elements with a class of the network name. We are taking the network name and passing it to the lower filter to make the name lowercase (another option would be to use the key name instead of lowercasing the network name).

So the links are clickable, the link to the social network is populated using the URL that is in the hash.

To wrap up, we close the for-loop and then close our ul element and, finally, close our macro tag.

Calling a Twig Macro

To call this macro right from the template it’s in, we use our output tags and the _self prefix on the macro name.

{{ _self.socialList(networks, "three-share") }}

This will call the socialList macro, passing in the networks hash, and the class name of three-share.

Our output will look something like this:


<ul class="three-share">
    <li class="twitter"><a href="http://twitter.com/happylager">Twitter</a></li>
    <li class="facebook"><a href="http://facebook.com/happylager">Facebook</a></li>
    <li class="instagram"><a href="http://instagram.com/happylager">Instagram</a></li>
</ul>

It’s not always practical to include the macro in the same template, especially you want to use this macro in other templates in your site. To centralize our macros, we can put them in their own template and import it.

Let’s put the socialList macro in a template called _macros.html (or _macros.twig), removing it from the previous template.

To include that template and get access to the macro, we need to import the _macros.html file in the template where we want to access the macro.

{% import '_macros' as siteMacros %}

We import it into the siteMacros variable so we have it handy and ready to use.

In our template, we can drop the _self prefix and instead call it like this:

{{ siteMacros.socialList(networks, "three-share") }}

And now not only do we have a macro that will generate a list of social networks for us, we also have it abstracted out into its own macros template so we can use it in any of our templates.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

Key Value Arrays in Twig

by Ryan Irelan

Twig doesn’t refer to a key, value array as an array. It calls it a hash.

A hash is one of several types of literals available in Twig. It has a key and a value. The pairs are separated by a comma and enclosed in curly braces.

{ key: value, key: value } 

Here’s a hash with some information about a page:

{ title: 'About', subtitle: 'About Mijingo', slug: 'about' }

Let’s assign this hash to a Twig variable using the set tag.

{% set page = { title: 'About', 
                subtitle: 'About Mijingo', 
                slug: 'about' } 
%}

To get the values out of the hash and output them to the template, we use the following syntax:

{{ variable_name.key }}

To get the title from the hash we assigned to the page variable, we use:

{{ page.title }}

This would output:

About

This example has the key as a name but the key could be a string, integer, or expression.

Hashes can also be nested. Here’s a good example from the Craft sample site Happy Lager (provided by Pixel & Tonic for everyone to use and explore):

{% set nav = {
    about:    { title: "The Brewery", desc: "About Us" },
    services: { title: "How It’s Made", desc: "Services" },
    work:     { title: "What’s On Tap", desc: "Our Work" },
    news:     { title: "Brew News", desc: "The Latest" }
} %}

We’re setting the nav variable to a nested hash. To access an individual value, we use the dot syntax again:

{{ nav.about.title }}

To iterate over the hashes in the nav variable, we use a for-loop (while adding in a little markup):


<nav>
    <ul>
    {% for item in nav %}
        <li>{{ item.title }}</li>
    {% endfor %}
    </ul>
</nav>

To add in the hash key as the slug for the URL, we use the for-loop again and the key,value pattern to access both the keys and the values.

We iterate over it like this (look at the Happy Lager base layout template for an example of this):


<nav>
    <ul>
    {% for slug, item in nav %}
        <li><a href="/{{ slug }}">{{ item.title }}</a></li>
    {% endfor %}
    </ul>
</nav>

I’ll dig through more of the Happy Lager site again soon and highlight more examples of how Twig works.

Ready to learn more about the Craft CMS?

My Craft Starter Pack is 4 ½ hours of premium learning that will get you started building sites with Craft for yourself, your company, or your clients.

Get Immediate Access

What are our customers saying?


"Just purchased your Flexible Twig course. Love it!"
Tyler Morrison
"Been enjoying @mijingo 's Learning Craft video tutorials. Feeling like I've got a good basic understanding of #craftcms Very impressive"
Laura Montgomery
"I bought your Craft Starter Pack a year and a half ago. Worth every dollar. In fact, I would've paid twice as much for it, because you saved me so much time."
Timothy Ingram
"Ben's knowledge of Craft combined with his relaxed and informal teaching style makes for a great learning experience."
Steve Abraham
"Ben puts a lot of thought into his teaching approach and has the ability to explain complex concepts in a way that just make sense"
Gareth Redfern
"Ben is great at taking a complex subject and breaking it down in a way that you can wrap your mind around. I thought that plugin development was something I would never understand, and happily Ben proved me wrong!"
Jonathan Melville
"I really appreciate all the videos and writing you have done. Your work has given me a jump start on my front end development business."
Shan Ricciardi

Perfect for Small Teams & Companies


Mijingo's courses are perfect as the training curriculum for both small teams and entire companies.

Our courses are offered in Team Packs (up to 5 people) and Company Packs (up to 25 people), so you can make one simple, fast purchase to train your entire staff.

Prices are listed with each course. Need more than 25 or something custom?

Send Your Requirements
Team Pack2-5 People
Company Pack6-25 People
Custom Pack25+ People