The Mijingo Blog

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

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:


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):

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

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):

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

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

Filed Under: Craft CMS, Twig