Escaping Characters in YAML Front Matter
Greetings, friends! There are some characters such as colons and hyphens that convey meaning in YAML files. Nowadays, it's common to see people use YAML inside markdown files in the form of YAML front matter. This was popularized by static site generators such as Jekyll, which powers GitHub Pages.
Front matter is a block of YAML or JSON code that adds metadata to a file, commonly a markdown file. When generating pages for my website, I use a package called frontmatter-markdown-loader that internally uses the front-matter package. The front-matter
package will parse the YAML at the top of my markdown files, so I can use the data in Vue components.
You may hear people talk about the JAMstack which means a technology stack consisting of JavaScript, APIs, and markup languages such as Markdown (ironic name, indeed). We can use Angular, React, Vue, or other frameworks as the "JavaScript" layer. Then, we can use markdown parsers such as markdown-it or remark to parse Markdown and transform it into HTML. Adding YAML front matter to markdown gives us extra data that we can use in our HTML!
The problem we can face when parsing YAML front matter is that we need to escape certain characters used by the YAML syntax such as colons and hyphens. Imagine if we had the following YAML front matter:
---
id: 1
tags:
- yaml
- frontmatter
- food
title: The Best Food: Pizza, Donuts, and Potatoes
description: Learn about the best food in existence
---
The syntax highlighting in the code snippet should already give us a hint that something is wrong. Compare this with YAML code that doesn't use a colon in the title
attribute.
---
id: 1
tags:
- yaml
- frontmatter
- food
title: The Best Foods Include Pizza, Donuts, and Potatoes
description: Learn about the best food in existence
---
You could remove the colon, but maybe we really want it to be there. Hope is not lost though! All we need to do is add a >
(greater than) symbol and put the line containing the colon on a new line.
---
id: 1
tags:
- yaml
- frontmatter
- food
title: >
The Best Food: Pizza, Donuts, and Potatoes
description: Learn about the best food in existence
---
The syntax highlighting changed again! This should definitely satisfy the YAML front matter parser 😌. The >
symbol is known as the folded style in the official YAML specification. The "folded style" is a type of block scalar style.
There are technically other ways to escape characters in YAML. However, they did not work for me when I encountered an issue with colons. In regular YAML, we can escape characters using double quotes around the text that contain a colon, but it still resulted in the YAML parser complaining 🤷.
I hope this article helped! The next time you see a colon or hyphen causing mischief in your code, fight back with the >
symbol!