Shopify / liquid

Liquid markup language. Safe, customer facing template language for flexible web apps.
https://shopify.github.io/liquid/
MIT License
11.1k stars 1.39k forks source link

Feature request: Better array functions #1202

Open davidwarrington opened 4 years ago

davidwarrington commented 4 years ago

Array creation and manipulation in Liquid is quite difficult as it currently stands. The method I see promoted everywhere to create arrays is to combine strings, then use the split function, but in situations where a non-string value is required you end up having to coerce a null value into an array using a method such as null | sort, followed by concatenating the values you actually want into said array.

I imagine that nothing can really be done to allow users to create arrays directly, but perhaps a more descriptive function would suit, such as {% assign array = null | to_array %}? In this case, it would return an empty array, but any non-null value would become the first array value.

If you were looping through a collection and all products needed to be pushed to a new array, you might write something like {% assign products = product | to_array: products %}, which would push the product to the end of the products array if it already exists, but create an array with product as the first value if it doesn't already exist.

Since we can already make arrays, they just require awkward methods to work with, I think it would make sense to allow users to do something like this. It would cut back on boilerplate code.

One thing my proposal doesn't address though is the ability to create nested arrays. Since we can't build objects, arrays at the very least give us one method of controlling how our data is structured, but nested arrays would provide even more flexibility and as such I hope that they can be considered too.

Curzey commented 4 years ago

The missing of better array methods is one of the most annoying things about liquid. +1 on this one 👍

matthijskooijman commented 3 years ago

Jekyll has push, pop, shift and unshift for array manipulation, sounds like importing those might solve the original request?

Curzey commented 3 years ago

@matthijskooijman would definitely be a good step in the right direction, at least.

er1 commented 3 years ago

1084, if merged, addresses the null | sort matter by allowing the literal empty to be a valid empty array.