Search code examples
jekyllliquid

How to use a variable as array index in Jekyll include


I have a data file containing objects that I want to use specified indexes in a Jekyll include.

My page is calling the include like so:

{% include components/header-filter.html items="0" %}

Where 0 is the index I want to use in this case.

My include is:

{% assign filterID = include.items %}
{% capture id %}{{ filterID }}{% endcapture %}
{% assign filter = site.data.filters[id] %}

This works until it gets to the 3rd line, at which point it outputs nothing.

What am I doing wrong?

Cheers!


Solution

  • I was able to get this to work with the following changes:

    1. Call the include with items as a integer not a string:

      {% include components/header-filter.html items=0 %}
      

      (note that this assumes you have no path issues with the location of the include. Running jekyll locally it insisted I put that in /_inlcudes)

    2. Remove the capture line and just pass filterID to the next line - it isn't needed and was possibly causing an issue:

      {% assign filterID = include.items %}
      {% assign filter = site.data.filters[filterID] %}
      
    3. And then to your comment "it outputs nothing", you'll need to output something (might have just been omitted from your example, but for completeness, let's assume filters has a filed called name):

      {{ filter.name }}