Question

I was wondering what is the proper way of finding the index of an item in an array is in a Liquid template, and selected related items based off of the index. Currently I'm able to calculate the value, but it seems to be a string and I can't then find other items in the array with the string. For example in a CMS:

{% for site_page in site.pages.all %}
      {% if site_page.id == page.id %}
        {% assign page_index = forloop.index0 %}
        {% capture previous_page_index %}
          {{ page_index | minus: 1 }}
        {% endcapture %}
        {% break %}
      {% endif %}
    {% endfor %}

The expected value can be found in previous_page_index (in this case 0) however, if i try to do something like site.pages.all[previous_page_index] I receive no output. If I do the same thing with a hardcoded index value: site.pages.all[0] it does yield an output. Does anyone have an idea/example on how this is supposed to be done in liquid?

Was it helpful?

Solution

Best I can figure is to use {% for item in array limit:1 offset:forloop.index0 %}. For example:

require 'liquid'    
chars = %w[a b c]
names = %w[alpha bravo charlie]
puts Liquid::Template.parse(<<DONE).render( 'chars'=>chars, 'names'=>names )
{% for c in chars %}
  {{c}} is
    {% for n in names limit:1 offset:forloop.index0 %}{{n}}{% endfor %}
{% endfor %}
DONE

…which produces…

  a is
    alpha

  b is
    bravo

  c is
    charlie

Editorial aside: ouch. What an ugly tempting language. I understand its goals, but the burden it places on users is heinous.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top