Add Values to a Sequence?

梦想与她 提交于 2020-04-07 23:42:00

问题


I've created a FreeMarker sequence in my template:

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

How do I add additional values to the sequence?


回答1:


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

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



回答2:


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.




回答3:


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)


来源:https://stackoverflow.com/questions/5512991/add-values-to-a-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!