BorisMoore / jsrender

A lightweight, powerful and highly extensible templating engine. In the browser or on Node.js, with or without jQuery.
http://www.jsviews.com
MIT License
2.67k stars 339 forks source link

Using {{for array}} with filtering #373

Closed hkvstore closed 2 months ago

hkvstore commented 2 months ago

I'd like to suggest supporting some JavaScript array functions, so it is not necessary to write and pass helper functions on rendering a template. The most common usage might be filtering, e.g.

{{for people filter=~ageRange minAge=20 maxAge=40}} => {{for people.filter(item => item.details.age > 20 && item.details.age < 40)}}...{{/for}}

Others usages:

{{for array sort=~compareFn}}...{{/for}} => {{for array.sort((a, b) => ...)}}...{{/for}}

{{for array reverse=true }}...{{/for}} => {{for array.reverse()}}...{{/for}}

{{for colors start=1 end=-1}}...{{/for}} => {{for colors.slice(1, -1)}}...{{/for}}

etc.

BorisMoore commented 2 months ago

Your examples with array.reverse() or colors.slice() should already work. But the array.sort() and people.filter() examples you show won't work, because you are declaring functions (in your example, arrow functions) inline, within the template markup. That is not something we will be able to support.