DRY Yaml
For the class that I’m teaching this Fall, I created a Jekyll site to hold the course materials. I’m in the camp that Jekyll can do anything and I want to use it always.
While working on variables in the config, I wondered if there’s a better way to write the following:
coursename: Intermediate Interactive Design
description: Intermediate Interactive Design, Informatics Department, University at Albany, Fall 2014
After some “concatenate Yaml” googling, I found that you can’t concatenate, but you can repeat nodes.
I tidied up and followed the patterns:
coursename: &course_name Intermediate Interactive Design
description:
- \*course_name
- Informatics Department
- University at Albany
- Fall 2014
Repeating nodes works by creating a keyword and placing it in the variable to be repeated. In this case, I used &course_name
. Next, I dropped *course_name
where I want &course_name
to be repeated.
You set the variable with &keyword
and recall it using *keyword
.
Repeated nodes (objects) are first identified by an anchor (marked with the ampersand - “&”), and are then aliased (referenced with an asterisk - “*”) thereafter. — Yaml Spec
You can repeat more than one node:
coursename: &course_name Intermediate Interactive Design
semester: &this_semester Fall 2014
description:
- \*course_name
- Informatics Department
- University at Albany
- \*this_semester
Now I can use either variable as I normally would and the repeated node will slide in smooth.
You might notice that I moved the description
to an array. This gives me a little more flexibility with output.
Now I can use {{ site.description | join: ", " }}
or even {{ site.description | join: "<br>" }}
to output the array nicely.