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 %}
Share:
24,894
Brian Hicks
Author by

Brian Hicks

Updated on July 09, 2022

Comments

  • Brian Hicks
    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
    kikito over 12 years
    The 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
    manatwork over 12 years
    Well, now it indeed looks like an answer, not a telegram. Updated my vote to reflect that.
  • Edward
    Edward almost 7 years
    I'm a bit confused by your snippet: can you just add _hash to your frontmatter variable to make it work?
  • kikito
    kikito almost 7 years
    @user3411192 Sorry I don't know what you mean.
  • Edward
    Edward almost 7 years
    where does this hash variable come from? I used item in my solution, though Jekyll nor Liquid documents the variable for iterating over key/value pairs in list items.
  • kikito
    kikito almost 7 years
    On 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 hashes link_hash. To iterate over the keys of each link_hash, I need the second loop, in which I used link. On my example, hash is being played by link.
  • Praveen
    Praveen almost 4 years
    This 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.