YAML front matter for Jekyll and nested lists

motleydev picture motleydev · Oct 6, 2012 · Viewed 16.8k times · Source

I have a set of nested yaml lists with something like the following:

title: the example
image: link.jpg
products:
 - top-level: Product One
   arbitrary: Value
   nested-products:
    - nested: Associated Product
      sub-arbitrary: Associated Value
 - top-level: Product Two
   arbitrary: Value
 - top-level: Product Three
   arbitrary: Value

I can loop through the products with no problem using for item in page.products and I can use a logic operator to determine if nested products exist - what I CAN'T do is loop through multiple nested-products per iteration of top-level

I have tried using for subitem in item and other options - but I can't get it to work - any ideas?

Answer

Rudy Velthuis picture Rudy Velthuis · Oct 15, 2012

Update

This example I just wrote (called index.html)

---
title: the example
products:
 - top-level: Product One
   arbitrary: Value
   nested-products:
    - nested: Associated Product
      sub-arbitrary: Associated Value
    - nested: Another associate
      sub-arbitrary: with its associated value
 - top-level: Product Two
   arbitrary: Value
   nested-products:
    - nested: nested product Two
      sub-arbitrary: Two's nested's associate value
 - top-level: Product Three
   arbitrary: Value
 - top-level: Product Four
   arbitrary: SomeValue
---
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
  <title>{{ page.title }}</title>
</head>

<body>

<h4>products:</h4>
<ul>{% for product in page.products %}
  <li>{{ product.top-level }}: {{ product.arbitrary }}{% if product.nested-products %}
    <ul>
    {% for nestedproduct in product.nested-products %}  <li>{{ nestedproduct.nested }}: {{ nestedproduct.sub-arbitrary }}</li>
    {% endfor %}</ul>
  {% endif %}</li>{% endfor %}
</ul>

<p>Hope that answers it</p>

</body>
</html>

Produces this:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
  <title>the example</title>
</head>

<body>

<h4>products:</h4>
<ul>
  <li>Product One: Value
    <ul>
      <li>Associated Product: Associated Value</li>
      <li>Another associate: with its associated value</li>
    </ul>
  </li>
  <li>Product Two: Value
    <ul>
      <li>nested product Two: Two's nested's associate value</li>
    </ul>
  </li>
  <li>Product Three: Value</li>
  <li>Product Four: SomeValue</li>
</ul>

<p>Hope that answers it</p>

</body>
</html>