squirrellyjs / squirrelly

Semi-embedded JS template engine that supports helpers, filters, partials, and template inheritance. 4KB minzipped, written in TypeScript ⛺
https://squirrelly.js.org
MIT License
555 stars 81 forks source link

Braces not working with pipes #256

Open perotom opened 12 months ago

perotom commented 12 months ago

Describe the bug I would like to use braces in my expressions to do some calculations. When using pipes this creates some issues.

To Reproduce Try to use braces mixed with pipes like:

{{((it.num_array | min) - 5) | format}}

One can reproduce it in the playground for the display array examples like:

{{(it.fruits | join(" + ")) + "test"}}

https://squirrelly.js.org/playground/

Expected behavior Braces should work as "usual" which normally are used to change evaluation order.

Package & Environment Details

nebrelbug commented 12 months ago

It's unfortunately not possible to combine filters with operations in that way. After a filter |, the only valid syntax is name (args) and then optionally more filters.

perotom commented 12 months ago

What a pity. Can you think of any other workaround? Or is it possible to use math functions like min max and then do some arithmetic? Thank you

nebrelbug commented 12 months ago

@perotom sure. The trick is to use multiple filters chained together, eg.

{{it.num_array | min | subtract(5) | format}} or {{it.fruits | join(" + ") | append("test")}}

perotom commented 9 months ago

@nebrelbug Sounds like a nice idea but let's just flip the subtraction in your example: {{5 | subtract(it.num_array | min) | format}} Sadly this simple example doesn't work. Overall it is an excellent library but this "simple" flaw really is a deal breaker. Any ideas for workarounds?

nebrelbug commented 9 months ago

@perotom yeah, Squirrelly unfortunately only supports top-level filters. Your best bet would be to use JS expressions inside of your filter. As an example:

{{ 5 | subtract(it.num_array.min()) | format }}

perotom commented 9 months ago

@nebrelbug Thanks for the idea, sadly we have a lot of subtractions with different variables so this approach won't work out in the long run. Do you think it is easy to add support for braces? Or does it break everything? Would be glad to add the support.

nebrelbug commented 9 months ago

It's unfortunately probably not feasible for this project :(.