Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access elements by index in an FTL Template

Tags:

freemarker

Need to access 1st and 2nd element of a list in the template.

My Java code:

myMap.put("key", Arrays.asList("val1", "val2");

My FTL Template:

<#list myMap?keys as key> 
${myMap[key][0]}, ${myMap[key][1]}

<-- the line above fails with undefined expression on myMap[key][0]. I checked and myMap[key] is a SimpleSequence. Also, tried ${myMap[key]?first} and that failed with the same error. Any ideas?

like image 870
shameed Avatar asked May 23 '12 18:05

shameed


People also ask

What syntax is used to access data using FreeMarker under a condition?

Special variables are variables defined by the FreeMarker engine itself. To access them, you use the . variable_name syntax.

Is FreeMarker template thread safe?

getTemplate(String) (and its overloads) does that (caching Template -s) for you, but the constructor of course doesn't, so it's up to you to solve then. Objects of this class meant to be handled as immutable and thus thread-safe.

How do you create a list on FreeMarker?

FreeMarker doesn't support modifying collections. But if you really want to do this in FreeMarker (as opposed to in Java), you can use sequence concatenation: <#assign myList = myList + [newItem]> . Here you create a new sequence that wraps the two other sequences.


1 Answers

[0] and [1] are fine for this, but it looks like that either the sequence has 0 elements, or those elements are null. What does ${myMap[key]?size} print? BTW, you can write ${myMap[key][0]!'some default'} if you want to get a value even if the item is non-existant or null.

like image 164
ddekany Avatar answered Sep 19 '22 14:09

ddekany