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 no | ups name | downs no | downs 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:
- Header Structure: We use
colspanto group the "ups" and "downs" sections in the top header, matching your desired format. - Loop Through Longer List: We iterate over
downs(the longer list) so we cover all items from both lists. - Index-Based Access: For each iteration, we grab
currentIndexfrom the loop. We use this to accessups[currentIndex]. - Null-Safe Handling: The
!""operator ensures that if the index is beyond the length ofups(like the 3rd iteration, whereupshas 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

