首页 > 解决方案 > Freemarker:使用拆分将字符串转换为列表然后迭代

问题描述

我需要遍历一个由“split”内置的列表,但我还没有成功。

我有两个共享一些相同日期的日期列表。使用“seq_index_of”作为“Vlookup”我能够找到相关性并获得两个列表中日期的索引。但是,“seq_index_of”给出了字符串、数字、布尔值或日期/时间值输出,而不是序列(供我迭代)。

我使用“拆分”将字符串转换为序列。不过,拆分不会真正完成这项工作。

first i use seq_index_of for the two lists:
this will give me the index of correlated dates.
<#assign result>
<#list list1 as L1> 
${list2?seq_index_of(L1)}
</#list>
</#assign>
---------------------------------------
next I iterate the result. for this, imagine "array" is the result from above:
ex 1. this does not work. cant iterate

<#assign array = "2020-10-02,2021-10-04,2022-10-04,2023-10-04" />
<#assign mappedArray_string = []>
<#list array?split(",") as item>
<#assign mappedArray_string += [item]>
</#list>

${"is_sequence: " + mappedArray_string?is_sequence?c}

<#--print the list-->
<#list mappedArray_string as m>
<#--i cant do ?string("MM/dd/yyyy") or ant other iteration
${m?string("MM/dd/yyyy")}
<#if m?has_next>${";"}<#else>${"and"}</#if>-->
<#with no iteration, this will work. not what i need-->
${m}
</#list>
+++++++++++++++++++++++++++++++++++++++++++++
ex 2. - this works with a regular numerical list
<#assign array = [100, 200, 300, 400, 500] />
<#assign mappedArray_numbers = []>
<#list array as item>
<#assign mappedArray_numbers += [item]>
</#list>

${"is_sequence: " + mappedArray_numbers?is_sequence?c}

<#--print the list-->
<#list mappedArray_numbers as m>
${m?string("##0.0")}<#-- able to iterate-->
</#list>```

expected:
date1 ; date2 ; date3 and lastdate

error:
For "...(...)" callee: Expected a method, but this has evaluated to a string (wrapper: f.t.SimpleScalar):
==> m?string  [in template "preview-template" at line 27, column 3]

----
FTL stack trace ("~" means nesting-related):
 - Failed at: ${m?string("MM/dd/yyyy")}

标签: freemarker

解决方案


如果您想列出list2也出现在中的项目list1,请执行此操作(因为 需要 FreeMarker 2.3.29 ?filter):

<#list list2?filter(it -> list1?seq_contains(it)) as d>
  ${d?string('MM/dd/yyyy')}
</#list>

2.3.29 之前:

<#list list2 as d>
  <#if list1?seq_contains(d)>
    ${d?string('MM/dd/yyyy')}
  </#if>
</#list>

推荐阅读