Adriano Monecchi
Adriano Monecchi

Reputation: 1200

How to iterate through a key's array within a variable's array in Jekyll?

Here's how I set up the page's front matter.

---

title: Test page
layout: default

image:
  - url: image01.png
    caption: 'Logo design'
    class: ['text-white']
    alt: 'An alt text'
  - url: image02.png
    caption: 'Website development'
    class: ['text-white', 'fullwidth-figure']
    alt: 'An alt text'

---

In the page layout this is how I iterate through the image: variable's array.

{% for image in page.image %}
<figure class="{% if image.class contains 'fullwidth-figure' %}fullwidth-figure{% else %}contained{% endif %}">
<img src="{{ site.photoset_url }}/{{ image.url }}" alt="{{ image.alt }}">
<figcaption>
{{ image.caption | textilize }}
</figcaption>
</figure>
{% endfor %}

This grabs all the stuff I need from the page's front matter list of associative arrays. So far, so good, but I was hoping to be able to iterate through the class: key array.

So if I set class: ['text-white', 'fullwidth-figure'] how can I check for the "fullwidth-figure" value and how could I "print" both values?

Upvotes: 0

Views: 623

Answers (1)

approxiblue
approxiblue

Reputation: 7122

You can use the join filter to print all classes (save yourself from a for-loop), then the unless tag to print "contained" only if "fullwidth-figure" is absent:

{% for image in page.image %}
<figure class="{{ image.class | join: ' ' }}{% unless image.class contains 'fullwidth-figure' %} contained{% endunless %}">
    <!-- image -->
</figure>
{% endfor %}

Upvotes: 1

Related Questions