Shopify / liquid

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

Additional string filters #778

Open chimericdream opened 8 years ago

chimericdream commented 8 years ago

I found myself needing to remove the last character of a string without knowing the length of the string in advance. At first, I thought I could use slice, but ran into the behavior mentioned in https://github.com/Shopify/liquid/issues/522. I then tried a few other things, including reversing the string, removing the first character, then reversing again. However, I didn't get the behavior I was looking for.

I think a few new filters would have made my issue easier to solve, as well as be good complementary filters to the ones which already exist.

clip (or some other name): Similar to slice, but allow for negative indices for people who want a Python-style method. str_reverse: Reverses a string replace_last, remove_last: Perform the same as their counterparts, replace_first and remove_first, except they obviously start at the end of the string and read backwards.

Merely having the str_reverse filter would make all the others above achievable (though a bit cumbersome) with existing filters, but I think all four of the filters would be great additions to the toolbox.

kainjow commented 8 years ago

You can do this with an assign:

{% assign str = "test" %}
{% assign num = str | size | minus: 1 %}
{{ str | slice: 0, num }}
JasonYao commented 7 years ago

Right, it's possible to do it with the two assigns and then the slice, but just from an end-user point of view, it was kind of surprising that there wasn't any *_last at all.

In terms of consistency, liquid already kind of has this withstrip: lstrip and rstrip. By adding the *_last filters, it would just be making the filters more consistent, and allow users from having to dig up old threads for the assign workaround.