Search code examples
jekyllliquid

Referencing include parameters in forloop construction


My project has various files in the _data folder (eg: list1.yml, list2.yml, list3.yml) and I'm looking for a flexible way to generate a for loop by passing a parameter into an include, like so:

{% include loop.html list="list1" %}

In loop.html I have:

{% capture listToUse %}{{ include.list }}{% endcapture %}
{% for item in site.data.listToUse %}
...
{% endfor %}

However, when I run this, nothing happens. Any help would be super appreciated!


Solution

  • site.data.listToUse is not a correct expression, you need to enclose your variable in brackets : site.data[listToUse].

    {% assign listToUse = include.list %}
    
    {% for item in site.data[listToUse] %}
      {{ item | inspect }}
    {% endfor %}