Tom Johnson
Tom Johnson

Reputation: 759

How to pass a frontmatter value into a for loop

I want to use a value in my frontmatter to specify a data file to loop through, but I can't get this to work.

I have a data file in _data/sidebars/sidebar1.yml. It contains:

- first
- second
- third

On a page I have this frontmatter:

---
title: My page
sidebar: site.data.sidebar.sidebar1
---

I want to use this code:

{% for entry in page.sidebar %}
* {{entry}}
{% endfor %}

However, this doesn't work. I've tried a number of things (involving assign and capture tags to define the page.sidebar content, but nothing seems to work).

The only thing that works is to do this:

{% if page.sidebar == "site.data.sidebars.sidebar1" %}
{% assign sidebar = site.data.sidebars.sidebar1 %}
{% endif %}

{% for entry in sidebar %}
* {{entry}}
{% endfor %}

However, I would like to avoid this extra code with the if statement, since it's easy to forget this and I would like to automate this more.

Any ideas on how to make this work?

Upvotes: 2

Views: 693

Answers (1)

David Jacquel
David Jacquel

Reputation: 52789

You have a typo in your front matter. It's :

sidebar: site.data.sidebars.sidebar1

not

sidebar: site.data.sidebar.sidebar1

You can even be less verbose.

In your front matter : sidebar: sidebar1

In your code :

{% assign sidebar = site.data.sidebars[page.sidebar]  %}

{% for entry in sidebar %}
  {{ entry | inspect }}
{% endfor %}

Upvotes: 3

Related Questions