shameed
shameed

Reputation: 113

Access elements by index in an FTL Template

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?

Upvotes: 8

Views: 18668

Answers (2)

Aswan
Aswan

Reputation: 76

Your problem is that you put the List into your 'myMap' object with the key: "key" then try and access it with they key: "keys".

This is why you were getting an undefined expression, to correct it:

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

or of course you could change your java code to

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

and use the ftl code as is.

Upvotes: 2

ddekany
ddekany

Reputation: 31152

[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.

Upvotes: 4

Related Questions