Freemarker:创建一个列表中包含列表的表

时间:2017-03-13 07:18:08

标签: java markdown freemarker

我目前有以下结构:

List<List<ClusterEntry>> clusters = new ArrayList<List<ClusterEntry>>();
//fill clusters and the list in clusters
input.put("clusters", clusters);

群集描述了我的群集和cluster.get(i)包含一个群集中的所有元素。对于报告,我想将此结果与freemarker一起输出到.md文件中。目标是使用尽可能多的列作为集群,并在每行中包含相应集群的条目。 我面临的问题是,我必须从外部列表开始,这意味着集群:

|<#list clusters as c>  Cluster ${c_index} | </#list>
|<#list clusters as c>-----|</#list>

这是我的标题在一行中的解决方案。如果我这样做:

|<#list clusters as c>  Cluster ${c_index} | 
</#list>

我的输出将是每个Cluster $ {c_index}

的单独行

所以现在我为每个群集名称都有一个列,但是如何在相应的行中填写?我需要在相应的单独列中包含每个不同的集群,但我不知道如何使用freemarker实现这一点,如下代码所示:

<#list clusters as c>  
<#list c as entry>| ${entry.id} |</#list> 
</#list> 

会导致一个集群在一行中的托管,而下一个集群在下一行中。我想要这个但是有列

1 个答案:

答案 0 :(得分:1)

如果我理解得很好,那么给出这个输入(使用http://freemarker-online.kenshoo.com/语法):

clusters=[["a1", "b1", "c1"], ["a2"], ["a3", "b3"], ["a4", "b4", "c4"]]
maxEntities=3

你想要这个输出(我用填充做了一点点......如果你需要,请使用?right_pad(n)):

| Cluster 1 | Cluster 2 | Cluster 3 | Cluster 4 |
|---        |---        |---        |---        |
| a1        | a2        | a3        | a4        |
| b1        |           | b3        | b4        |
| c1        |           |           | c4        |

嗯,它不是很漂亮,因为你想在模板中旋转表格。但是,我们的想法是外部循环遍历实体索引,内部循环遍历集群。 (顶部还有两个异常行,显示了群集名称和标题分隔符行。)

|<#list clusters as c> Cluster ${c?counter} <#sep>|</#list>|
|<#list clusters as c>--- <#sep>|</#list>|
<#list 0 ..< maxEntities as entityIndex>
|<#list clusters as c> ${c[entityIndex]!} <#sep>|</#list>|
</#list>

BTW,maxEntities可以在模板中计算出来,如果情况更好:

<#function maxListItemSize items>
  <#local max = 0>
  <#list items as item>
    <#local size = item?size>
    <#if max < size>
      <#local max = size>
    </#if>
  </#list>
  <#return max>
</#function>

然后你有<#list 0 ..< maxListItemSize(clusters) as entityIndex>