31

I've created a FreeMarker sequence in my template:

<#assign x = ["red", 16, "blue", "cyan"]>

How do I add additional values to the sequence?

3 Answers 3

62

You have to create a new sequence by concatenating x and a sequence containing only the new element:

<#assign x = x + [ "green" ] />
4
  • 2
    @Vicky The SequenceModel class has add methods, but nothing exists in the syntax to invoke them. So my solution is the only way to do it (short of writing Java code and add it to the model of course). Apr 1, 2011 at 13:18
  • 1
    Yes, sequences (and hashes) are immutable as far as the template language is concerned. SimpleSequence is just one of the sequence implementations, and SimpleSequence.add is only meant to be used to initialize a sequence in Java.
    – ddekany
    Jan 10, 2015 at 13:45
  • 1
    I meet a problem lately, x+["green"] in <#list> for 3000 times bring a performance problem, but ["green"] + x fix this problem! Its about left-hand and right-hand. Btw @LaurentPireyn 's solution is another good way.
    – soytian
    Jun 13, 2018 at 4:00
  • Thanks @soytian for suggesting your fix, it really works, I went from 1 minutes for 1000 "right-hand appends" (ie: x+["green"]) to 20 seconds for 1000 "left-hand appends" (ie: ["green"]+x) Mar 4, 2020 at 15:11
16

FreeMarker is basically a write-once language. It tries very hard to make it impossible to manipulate data, and that includes modifying arrays or maps, etc.

You can work around this, however, through concatenation and reassignment:

<#assign my_array = [] />
<#list 1..10 as i>
  <#assign my_array = my_array + ["value " + i] />
</#list>

This should result in an array containing "value 1" through "value 10". If this seems inelegant it's because it was intended that way. From FreeMarker's ideological perspective, once you've started building arrays, etc., you've moved beyond what the templating language should be doing and into what the models, controllers, helper classes, etc., should be doing in Java code. Working in FreeMarker can become intensely frustrating the more you deviate from this viewpoint.

From http://freemarker.sourceforge.net/docs/app_faq.html#faq_modify_seq_and_map:

The FreeMarkes Template Language doesn't support the modification of sequences/hashes. It's for displaying already calculated things, not for calculating data. Keep templates simple. But don't give it up, you will see some advices and tricks bellow.

5

Laurent's answer is correct and perfectly acceptable. But you can also add a value using shorthand:

<#assign x += ["green"]>

Now the sequence will look like:

Sequence (5)
  0 = "red" (String)
  1 = 16 (BigDecimal)
  2 = "blue" (String)
  3 = "cyan" (String)
  4 = "green" (String)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.