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?
Special variables are variables defined by the FreeMarker engine itself. To access them, you use the . variable_name syntax.
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.
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.
[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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With