You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FreeMarker实现双列表在同一表格展示的技术求助

How to Generate a Merged Table with Unequal-Length Lists in FreeMarker

I have two lists:

  • ups = {up1, up2} (2 items)
  • downs = {down1, down2, down3} (3 items)

I need to generate a table that aligns items by their index, leaving empty cells for the shorter list once it runs out. The desired output looks like this:

ups noups namedowns nodowns name
${up1.no}${up1.name}${down1.no}${down1.name}
${up2.no}${up2.name}${down2.no}${down2.name}
${down3.no}${down3.name}

My current code only loops through downs and doesn't handle the ups items correctly:

<#list downs as down>
<tr>
<td>ups?</td>
<td>${down.no}</td>
<td>${down.name}</td>
</tr>
</#list>

How can I adjust this code to produce the table I need?


Got it, let's work through this. Since your two lists have different lengths, we'll loop through the longer list (downs here) and use the loop index to pull matching items from ups—only if that index exists in ups. FreeMarker's loop variable gives us access to the index with ?index, which we'll use for this.

Here's the modified, working code:

<table>
  <!-- Table Headers -->
  <thead>
    <tr>
      <th colspan="2">ups</th>
      <th colspan="2">downs</th>
    </tr>
    <tr>
      <th>no</th>
      <th>name</th>
      <th>no</th>
      <th>name</th>
    </tr>
  </thead>
  <!-- Table Body -->
  <tbody>
    <#list downs as down>
      <#assign currentIndex = down?index>
      <tr>
        <!-- Render ups item if index is within ups' bounds, else empty cells -->
        <td>${ups[currentIndex].no!""}</td>
        <td>${ups[currentIndex].name!""}</td>
        <!-- Always render downs item details -->
        <td>${down.no}</td>
        <td>${down.name}</td>
      </tr>
    </#list>
  </tbody>
</table>

Let me break down the key parts:

  1. Header Structure: We use colspan to group the "ups" and "downs" sections in the top header, matching your desired format.
  2. Loop Through Longer List: We iterate over downs (the longer list) so we cover all items from both lists.
  3. Index-Based Access: For each iteration, we grab currentIndex from the loop. We use this to access ups[currentIndex].
  4. Null-Safe Handling: The !"" operator ensures that if the index is beyond the length of ups (like the 3rd iteration, where ups has no item), it outputs an empty string instead of throwing an error.

If you ever end up with ups being longer than downs, just swap the loop to iterate over ups instead, and apply the same null-safe logic to the downs items.

内容的提问来源于stack exchange,提问作者CappaFeng

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 10:21:28