How to create an array in a for loop in Liquid?
Asked Answered
L

2

27

I'm trying to create an array from a list of objects using Liquid syntax:

{% for operation in menuItems %}
      {% assign words1 = operation.Title | split: '_' %}
      {% assign controllerName = words1 | first %}
      {% assign controllersTmp = controllersTmp | append: '_' | append: controllerName %}
{% endfor %}

I want to split the controllersTmp to get my array, but at this point my controllersTmp is empty.

Any help ?

Litch answered 21/12, 2016 at 13:9 Comment(0)
D
39

You can directly create a new empty array controllers and concat to it your controllerName converted into an array using the workaround split:''. The result is directly an array, without the extra string manipulations.

{% assign controllers = '' | split: '' %}
{% for operation in menuItems %}
    {% assign controllerName = operation.Title | split: '_' | first | split: '' %}
    {% assign controllers = controllers | concat: controllerName %}
{% endfor %}
Doc answered 21/12, 2016 at 15:48 Comment(2)
Maroine, was this working in API Management template as requested? I tried to do a similar thing but it looks like concat cannot be usedMarivaux
If controllerName isn't an array itself (which I don't think it would be in the OP's question), you'd need to use append in the last assign. And you could skip the split in the first assign.Heterosexuality
H
6

What worked for me

{% assign otherarticles = "" | split: ',' %}
{% assign software_engineering = "" | split: ',' %}

{% for file in site.static_files %}
  {% if file.extname == ".html" %}
    {% if file.path contains "software_engineering" %}
       {% assign software_engineering = software_engineering | push: file %}
    {% else %}
      {% assign otherarticles = otherarticles | push: file %}
    {% endif %}
  {% endif %}
{% endfor %}

Habergeon answered 5/6, 2020 at 17:7 Comment(2)
What is the definition of push filter? I get "undefined filter push"Matteson
I believe push is a filter added by Jekyll: jekyllrb.com/docs/liquid/filtersButcher

© 2022 - 2024 — McMap. All rights reserved.