Search code examples
arraysfreemarker

How to removing value in array using Free marker?


I am using the free marker template language 2.3.1. I want to remove a value from an array. Can you give any suggestions?

Sample code like:

<#assign array=[0]> <#list array as a>${a}    <#assign array = array +[1]+[2]> <#assign array = array - [0]>    <#list array as b> ${b}</#list></#list>

O/P: 0 1 2

What will I have to replace with <#assign array = array - [0]> line?


Solution

  • Hopefully 2.3.1 is a typo, and I will assume that it's at least 2.3.21. Also because array-like things are called sequences in FreeMarker, I will use that term. So, you can't modify sequences in FreeMarker, but you can create new sequences from a sequence, via slicing like seq[from ..], seq[from .. toInclusive], seq[from ..< toExclusive], and seq[from ..* length], or via concatenation, like seq1 + seq2. Thus you can in effect remove an element: seq[0 ..< removedIndex] + seq[removedIndex + 1 ..]. All these operations just create "views", rather than modifying anything, and each time you apply them, the resulting sequence will become slower to read, so don't apply them for, like, tens or hundreds of times.

    See these in the Manual: https://freemarker.apache.org/docs/dgui_template_exp.html#dgui_template_exp_sequenceop

    Also, you can experiment with things quickly here: https://try.freemarker.apache.org/