Justin Duke

Embedding Markdown in YAML

Barback’s data is all stored internally as YAML. This isn’t for any particularly interesting technical reason: I just like writing it more than JSON. It means when I want to create a new recipe, I can write something like:

- name: Naked and Famous
  source: http://www.letsdrinkabout.it/sara-benincasa/
  ingredients:
  - 2cl Aperol
  - 2cl Mezcal
  - 2cl Yellow Chartreuse
  - 2cl Lime juice
  directions: "Combine all ingredients in a shaker, add ice and shake until well chilled. Strain into a chilled cocktail glass. Garnish with a lime wedge."
  garnish: "lime wedge"
  glassware: coupe

I’m in the process of converting directions for recipes from the prosaic format as seen above to something akin to an ordered list (like, you know, actual directions.) So instead of:

Combine all ingredients in a shaker, add ice and shake until well chilled. Strain into a chilled cocktail glass. Garnish with a lime wedge

It could be:

  1. Combine all ingredients in a shaker.
  2. Add ice and shake until well chilled.
  3. Strain into a chilled cocktail glass.
  4. Garnish with a lime wedge.

This lead to an interesting question: how do I actually do this in the confines of YAML?

Most markdown is fine in YAML — I was already embedding inline Markdown like em and strong in it. However, ordered lists need newlines in Markdown. The above list would be represented as follows:

1. Combine all ingredients in a shaker.
2. Add ice and shake until well chilled.
3. Strain into a chilled cocktail glass.
4. Garnish with a lime wedge.

And YAML doesn’t really like multi-line strings, right?

Turns out, the solution is pretty simple. You can express a scalar as being literal using |, which means — amongst other things — that newlines will be preserved. So all you need to do to preserve the Markdown formatting within YAML is use this to kick off your multi-line string, as follows:

- name: Naked and Famous
  source: http://www.letsdrinkabout.it/sara-benincasa/
  ingredients:
  - 2cl Aperol
  - 2cl Mezcal
  - 2cl Yellow Chartreuse
  - 2cl Lime juice
  directions: |
    1. Combine all ingredients in a shaker.
    2. Add ice and shake until well chilled.
    3. Strain into a chilled cocktail glass.
    4. Garnish with a lime wedge.
  garnish: "lime wedge"
  glassware: coupe
Liked this post? You should subscribe to my newsletter and follow me on Twitter.

(I've got an RSS feed, too, if you'd prefer.)