Access yaml key name with liquid

Viewed 35

Is it possible to access the key names along with key values from a yaml file using liquid?

For example from a .yaml file that looks like this:

- type: a
  id: b
  author: c
  website: d

Have liquid code that looks something like this:

{%- for item in YAMLFILE -%}
 {{ item.??? }} = {{ item.??? }}
{%- endfor -%}

with the following output:

type = a
id = b
author = c
website = d

I am trying to do this this way because my yaml file has different key names along with values and it would be a pain having to embed a bunch of different if else statements to account for every possible key name.

Thank you all so much!

1 Answers

Assuming your yaml file is in _data/test, you can use:

{% for list in site.data.test %}
  {% for item in list %}
    {{ item[0] }} = {{ item[1] }}
  {% endfor %}
{% endfor %}

item[0] is the key and item[1] is the value. It will work with different number of keys and names in each list.

Also be aware that four spaces in Markdown formats the content of the second for loop as a code block. Simply do not indent if putting this code in a Markdown file.

Related