mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.48k stars 634 forks source link

Augment 'first' & 'last' filter with param n - Jinja/Twig feature parity #1463

Open webketje opened 2 months ago

webketje commented 2 months ago

The following is salvaged from a meaningful comment on a now-deleted PR that is a good candidate for increased feature parity

This is really easy to add in user-code if desired:

constenv = new nunjucks.Environment()
env.addFilter('limit', function(str, n) {
  return arr.slice(0, n)
});

Nunjucks' goal is to have full Jinja2 compatibility, and eventual Twig compatibility. The Twig slice filter behaves a lot like Javascript's arr.slice(start, end), however Jinja's slice creates an array of arrays.

In effect, it can be argued that Nunjucks is missing a feature to get n items from the start/end of a string/array because in Python Jinja2, this can be achieved using the square bracket notation source_list[:N]. Given that Nunjucks does not allow this, a better proposal IMO would be to "augment" the first and last filters so they can take an additional signature with an argument, like:

{{ myarr|first(10)) }}
{{ myarr|last(5)) }}

Originally posted by @webketje in https://github.com/mozilla/nunjucks/issues/1366#issuecomment-1290549739