curious
curious

Reputation: 831

Nested "for" loop inside "if" condition in Liquid/Jekyll

I'm getting syntax error while trying to generate site. Do you have any ideas what can be wrong here?

Error: Liquid syntax error: Unknown tag 'elsif'

{% if page.title == "Tags" %}
    {% for tag in site.tags %}
{% elsif page.title == "Categories" %}
    {% for tag in site.categories %}
{% endif %}
  <a href="#{{ tag[0] | slugify }}">{{ tag[0] }}</a>
  {% endfor %}

Upvotes: 1

Views: 2626

Answers (2)

Ankit R Gadiya
Ankit R Gadiya

Reputation: 489

You have got it all wrong. The nested loops does not work this way. It should start and end inside the same conditional.

if conditional
    for loop

    endfor
endif

something like this.

So, the correct way to do it should be this

{% if page.title == "Tags" %}
    {% for tag in site.tags %}
        <a href="#{{ tag[0] | slugify }}">{{ tag[0] }}</a>
    {% endfor %}
{% elsif page.title == "Categories" %}
    {% for tag in site.categories %}
        <a href="#{{ tag[0] | slugify }}">{{ tag[0] }}</a>
    {% endfor %}
{% endif %}

This code should do exactly what you want correctly but there is a better approach as answered by JJJ

Upvotes: 1

JJJ
JJJ

Reputation: 33163

You can't start a loop conditionally like that, control blocks must be properly nested. To accomplish what you're trying to do you could do:

{% if page.title == "Tags" %}
  {% assign data = site.tags %} 
{% elsif page.title == "Categories" %}
  {% assign data = site.categories %}
{% endif %}

{% for tag in data %}
  <a href="#{{ tag[0] | slugify }}">{{ tag[0] }}</a>
{% endfor %}

Upvotes: 2

Related Questions