Iterate over hashes in liquid templates
24,894
Solution 1
When you iterate over a hash using a variable called hash
, hash[0]
contains the key and hash[1]
contains the value on each iteration.
{% for link_hash in page.links %}
{% for link in link_hash %}
<a href="{{ link[1] }}">{{ link[0] }}</a>
{% endfor %}
{% endfor %}
Solution 2
I would define them like this in YAML:
links:
demo: http://www.github.com/copperegg/mongo-scaling-demo
And then iterate:
{% for link in page.links %}
<a href="{{ link[1] }}">{{ link[0] }}</a>
{% endfor %}
Author by
Brian Hicks
Updated on July 09, 2022Comments
-
Brian Hicks almost 2 years
I'm writing a site in Jekyll, which uses Liquid.
I have front matter for pages that I'd like to look like this:
--- title: Designing algorithms that scale horizontally speaker: Luke Ehresman, CopperEgg category: notes.mongodallas.talks links: - demo: http://www.github.com/copperegg/mongo-scaling-demo layout: talknotes ---
In Liquid, the links section of YAML comes through as:
[{'demo' => 'http://www.github.com/copperegg/mongo-scaling-demo' }]
I'd like to be able to iterate over the array, doing something like this:
<a href="{{ link.value }}">{{ link.key }}</a>
But any ideas I've had so far have failed me.
-
kikito over 12 yearsThe code works, just not like you seem to expect. Notice that I said iterate over a hash. I've added more code to give you context.
-
manatwork over 12 yearsWell, now it indeed looks like an answer, not a telegram. Updated my vote to reflect that.
-
Edward almost 7 yearsI'm a bit confused by your snippet: can you just add
_hash
to your frontmatter variable to make it work? -
kikito almost 7 years@user3411192 Sorry I don't know what you mean.
-
Edward almost 7 yearswhere does this
hash
variable come from? I useditem
in my solution, though Jekyll nor Liquid documents the variable for iterating over key/value pairs in list items. -
kikito almost 7 yearsOn the question, the front matter has a "list of hashes" called
links
. The first loop iterates over that list (page.links
), getting one hash each time. I called each of these hasheslink_hash
. To iterate over the keys of eachlink_hash
, I need the second loop, in which I usedlink
. On my example,hash
is being played bylink
. -
Praveen almost 4 yearsThis is definitely the better way to go. The YAML in the question redundantly has a hash within a list under
links
. The list can be eliminated. The top answer is confusing because it tries to first iterate over the list, and then iterates over the hash, which is completely unnecessary, and which this answer avoids.