Evan
Evan

Reputation: 6115

Accessing an array with a variable in Jekyll/Liquid templating

I have the following code in my template:

  {% for post in site.posts %}
    {% capture num_colors %}{{ site.colors | size }}{% endcapture %}
    {% capture color_index %}{{ forloop.index0 | mod: num_colors }}{% endcapture %}

    <a href="{{ post.url }}" class="post-box" rel="bookmark" title="{{ post.title }}">
      <div class="post-block {{ site.colors[color_index] }}">
        <div class="contents">
          <div class="cat-tag">
            {{ post.categories[0] | upcase }}
          </div>

          <h2>{{ post.title }}</h2>
        </div>
      </div>
    </a>
  {% endfor %}

This keeps returning nothing: {{ site.colors[color_index] }} even though num_colors, color_index, and site.colors will all return the correct things when I try and print them.

colors is defined in my _config.yml as:

colors: [light_blue, coral, yellow, teal, blue, deep_blue]

I'm using a plugin to get modulus. Basically I just want to attach a class for each post that will start over when its gone beyond the total number of colors. This seems straightforward so I'm confused.

Upvotes: 0

Views: 1067

Answers (1)

David Jacquel
David Jacquel

Reputation: 52789

Replace

{% capture num_colors %}{{ site.colors | size }}{% endcapture %}
{% capture color_index %}{{ forloop.index0 | mod: num_colors }}{% endcapture %}

by :

{% assign num_colors = site.colors | size %}
{% assign color_index = forloop.index0 | modulo: num_colors %}

Upvotes: 1

Related Questions