Scott Simpson
Scott Simpson

Reputation: 3850

How to concatenate the value of iterator inside liquid tag (Jekyll)

I am looping through a Yaml object and need to append the value of 'i' to the address the proper object.

<div class="chapter">
  {% for i in (1..7) %}
    <strong class="title">{{ page.chapters.title + i }}</strong>
    <ul>
      {% for topic in page.chapters.ch + i %}
        <li>
          {{ topic }}
        </li>
      {% endfor %}
    </ul>
  {% endfor %}
</div>

The data:

---
layout: default
title: Home
chapters:
  title1: "CHAPTER 1: LEADERSHIP"
  ch1:
    - Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    - Aliquam tincidunt mauris eu risus.
    - Vestibulum auctor dapibus neque.

  title2: "CHAPTER 2: THE EXPERIENCE"
  ch2:
    - Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    - Aliquam tincidunt mauris eu risus.
    - Vestibulum auctor dapibus neque.
---

The part that doesn't work is this:

{% for topic in page.chapters.ch + i %}

I need the value of ch to be ch1, ch2, etc…

Upvotes: 1

Views: 413

Answers (2)

Scott Simpson
Scott Simpson

Reputation: 3850

I got this working by updating the data model and creating a nested loop:

---
chapters:
  - title: "CHAPTER 1: LEADERSHIP"
   chapterList:
     - Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
     - Aliquam tincidunt mauris eu risus.
     - Vestibulum auctor dapibus neque.

 - title: "CHAPTER 2: THE EXPERIENCE"
   chapterList:
     - Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
     - Aliquam tincidunt mauris eu risus.
     - Vestibulum auctor dapibus neque.
---
<div class="chapter">
  {% for chapter in page.chapters %}
   <strong class="title">{{ chapter.title }}</strong>
     <ul>
        {% for chapterItem in chapter.chapterList %}
         <li>
            {{ chapterItem }}
         </li>
         {% endfor %}
     </ul>
  {% endfor %}
</div>

Upvotes: 1

Erik Gillespie
Erik Gillespie

Reputation: 3959

You can access YAML as Ruby associative arrays, but inline operations using the + operator won't work. You can remedy that by using the append filter.

Try this:

{% assign ch_key = 'ch' | append: i %}
{% for topic in page.chapters[ch_key] %}
    <li>{{ topic }}</li>
{% endfor %}

Upvotes: 0

Related Questions