javascripttemplatingnunjucks

Getting specified range of an array in Nunjucks


{% set array = [0,1,2,3,4,5,6,7,8,9] %}

I want a range of this array. Just like this:

[2,3,4,5]

In JavaScript, it is so easy to be done with the slice method. But in Nunjucks, slice works different. I don't know how to take a range of this array.


Solution

  • It doesn't work for this case. That slice doesn't work like JS slice.

    Actually it is the JS slice, and we can use it directly in NJK templates.

    Note the dot syntax:

    {% set array = ['a', 'b', 'c', 'd', 'e'] %}
    
    {{ array.slice(2, 5) }}
    

    Output (3rd to 5th items):

    c,d,e
    

    What can be confusing is that Nunjucks has its own slice, which is a totally unrelated filter.

    Note the pipe syntax:

    {% for items in array | slice(2, 5) %}
      {{ items }}
    {% endfor %}
    

    Output (2 slices with the shorter slice padded by "5"):

    a,b,c
    d,e,5