问题
I have a list in free marker as below:
<#assign listVar = ["v1", "v2", "v3", "v4" ] />
From the above list I just want the sub list as v1 and v2.
I have been wandering to get the sub list in free marker. But couldn't managed to find.
Any help would be appreciate.
回答1:
If you really want to make that slice based on indexes:
<#assign listVar = ["v1", "v2", "v3", "v4" ] />
<#assign sublistVar = listVar[0..1] />
See Freemarker Sequence slicing.
But beware, it will stop with error if the index is out of range. Depending on what you need this for, you may want to use ?chunk(2)
instead.
Update: As of avoiding index-out-of-bounds error, in FreeMarker 2.3.21 you can issue listVar[0..*2]
, which will slice out 2 items, or less if there's less available. (Also exclusive-end slicing can come handy: listVar[0..<2]
)
回答2:
You can use the index
variable when you list the sequence.
<#assign listVar = ["v1", "v2", "v3", "v4" ] />
<#list listVar as aVar>
<#if aVar_index > 2><#break/></#if>
</#list>
You can also partition the sequence using chunk
. This will split the sequence in multiple sequences of the given size.
<#assign partitions = listVar?chunk(2) />
<#assign firstPartition = partitions?first />
Source: FreeMarker Manual
However, it is better to filter the data before passing it to the template.
来源:https://stackoverflow.com/questions/18458417/get-sub-list-from-a-list-in-freemarker