简体   繁体   中英

With jekyll / liquid how to get all keys of a yml hash

I have this yaml

param1:
  key1: value1
  key2: value2

param2:
  key1: value1
  key2: value2

param3:
  key1: value1
  key2: value2

how can I get all the keys with a liquid?

The expected result would be

param1,param2,param3

Any idea?

  • very ugly solution: {% for %} on the collection and concat the keys...
  • acceptable alternative solution: create a liquid filter "keys" ... sound too big that it does not actually exists ...

I suggest you an other format for your yml file

- id: param1
  key1: value1
  key2: value2

- id: param2
  key1: value1
  key2: value2

- id: param3
  key1: value1
  key2: value2

Then you could use {{ site.data.file | map: "id" | join: "," }} {{ site.data.file | map: "id" | join: "," }}

Ok, I implemented a small filter to get the hash keys :

https://github.com/dalenys/jekyll-keys-filter

Just have to write something like:

{{ hash | keys }} 

I used your "ugly solution" of looping through the collection elements:

{%  for hash in site.data.file -%}
    {{hash[0]}},
{%- endfor %}

If you want to get rid of the trailing ',':

{%  for hash in site.data.file limit: 1 -%}
    {{hash[0]}}
{%- endfor %}
{%- for hash in site.data.file offset: 1 -%}
    ,{{hash[0]}}
{%- endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM