privatemachine
privatemachine

Reputation: 53

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!

Upvotes: 4

Views: 2702

Answers (3)

Garytech
Garytech

Reputation: 338

Use the forloop helper

  • forloop.length -- length of the entire for loop
  • forloop.index -- index of the current iteration
  • forloop.index0 -- index of the current iteration (zero based)
  • forloop.rindex -- how many items are still left?
  • forloop.rindex0 -- how many items are still left? (zero based)
  • forloop.first -- is this the first iteration?
  • forloop.last -- is this the last iteration?
{% for offer in site.data.companies %}
  <li data-target="#carouselExampleCaptions" data-slide-to="{{forloop.index0}}"></li>
{% endfor %}

This will give

<li data-target="#carouselExampleCaptions" data-slide-to="0"></li>

<li data-target="#carouselExampleCaptions" data-slide-to="1"></li>

<li data-target="#carouselExampleCaptions" data-slide-to="2"></li>

...

Upvotes: 1

GeorgeButter
GeorgeButter

Reputation: 2589

You can make this by 'cutting out the middle man' {% include components/header-filter.html items=0 %}

{% assign filter = site.data.filters[include.items] %}

The reason yours wasn't working is because the capture was converting it into a string. You can convert a string to a integer with a maths filter. For example: {% assign id = id | plus: 0 %} the value of it wont change but liquid will now treat it as an integer.

Alternatively you can just call it as an integer by omitting the quote marks. {% include components/header-filter.html items=0 %}

Upvotes: 1

busse
busse

Reputation: 1777

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

Upvotes: 1

Related Questions