Iterate over hashes in liquid templates

LiquidJekyll

Liquid Problem Overview


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.

Liquid Solutions


Solution 1 - Liquid

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 - Liquid

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 %}

Solution 3 - Liquid

  {% for link in page.links %}
      {% for item in link %}
        <a href="{{ item[0] }}">{{ link[1] }}</a>
      {% endfor %}
    {% endfor %}

I had a very similar issue, but I had multiple items in my variable so I used the undocumented item variable and it did the job.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrian HicksView Question on Stackoverflow
Solution 1 - LiquidkikitoView Answer on Stackoverflow
Solution 2 - Liquidyegor256View Answer on Stackoverflow
Solution 3 - LiquidEdwardView Answer on Stackoverflow