Using Variables in YAML Front Matter

May 30, 2014

What is Front Matter?

I didn’t know this until just now, but the name comes from book design, where the front matter is just all the stuff before the actual body of the book. This includes the table of contents, title pages, copyright info, etc. It’s essentially all the metadata of the book.

Likewise, the YAML front matter common in static-site generators like Middleman is the metadata of the current page. In my case that usually ends up being post pages where some of the dynamic data is defined:

layout: post
title: Using Variables in YAML Front Matter
date: 2014-05-30 09:08
tags: yaml, middleman

This makes it super easy to have various HTML layouts that you can assign to any page on your site. It also gives us the date and title options which are useful for the index, file structure, and other obvious benefits.

Setting Custom Variables

I have 4 social media icon SVGs on my portfolio/main index page, and I’m currently using each of them twice - one for the contact drop-down menu, and another for the contact section at the bottom.

As you can imagine, that clunked up the HTML pretty bad and it was immediately a giant pain to try and find or move anything. I wanted to DRY it up, and I knew that I could do that with Middleman.

It only took 3 steps.

1) The first thing I did was list each of the icons by name in the front matter:





2) Then I added the cumbersome svg codes to set the variables for each:

github: <svg version="1.1" id="Layer_1" xmlns="" xmlns:xlink="" x="0px" y="0px"
                width="22" height="20" viewBox="0 0 99.441 99.44" enable-background="new 0 0 99.441 99.44" xml:space="preserve"><path id="github" fill="#fff" d="M64.507,95.749c-2.439,0.474-3.303-1.026-3.303-2.307c0-1.584,0.053-6.763,0.053-13.197
linkedin: <svg> ...

3) After that it was simply a matter of calling “” and passing the custom variable in its place in Erb:

<a href=""><%= %>Github</a>

Now the code base is much more DRY and modular, and the generated HTML is producing the expected behavior.

You can do this in Jekyll too, but there are a few differences (basically just step 3) so check out their docs if thats what you’re into.

For more info on the Middleman front matter, see the relavent section in the Middleman docs.

– Mike