Using Liquid variables in Jekyll page frontmatter
When creating and publishing a set of single-sourced documentation using Jekyll, custom page and site-wide YAML data items come in handy for all sorts of data that you want to define and (re)use throughout the pages. However, there is one limitation to this – if Liquid variables are used in page frontmatter, those will not be converted by Jekyll. So, imagine you are maintaining a set of single-sourced documentation for multiple products, and your meta description is retrieved from a variable named
shortdesc in page frontmatter, for example:
The above item uses the
product variable defined in the config file to output the corresponding product name in the meta description of the generated page. However, this is not natively supported by Jekyll.
One solution that seems to be quite comprehensive is jekyll-conrefifier that allows you to use liquid variables not only in the frontmatter, but in a whole range of other places in Jekyll (including data files). This, though, turned out too good to be true in my case as it works with Jekyll 2.x, while the Jekyll version I am using is 3.5.2.
Fortunately, I was able to find something that does the job, and does so in 10 lines of code effectively. It is a Jekyll filter named liquify. The trick is – within your HTML page template you need to add
| liquify to any variable you expect to contain a reference to another variable. To put it simply:
We have already seen that
site.product and therefore has a variable that needs to be parsed additionally. The liquify filter will simply liquid-parse the variable and render the proper output. A neat, quick and easy solution for the issue.