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

如何使用Twig将两个数组内容并排渲染为HTML表格

解决方案

原代码的问题在于分别遍历last和primary数组,每个元素单独生成一行,无法实现两行数据并排的效果。你可以按索引同步遍历两个子数组实现需求,参考代码如下:

<table>
    {# 取两个子数组的最小长度作为遍历行数,避免索引越界 #}
    {% set maxRow = min(CompareArray.last|length, CompareArray.primary|length) %}
    {% for rowIndex in 0..(maxRow - 1) %}
    <tr>
        {# 渲染当前行last数组的所有字段 #}
        {% for value in CompareArray.last[rowIndex] %}
        <td>{{ value }}</td>
        {% endfor %}
        
        {# 中间分割列 #}
        <td>####</td>
        
        {# 渲染当前行primary数组的所有字段 #}
        {% for value in CompareArray.primary[rowIndex] %}
        <td>{{ value }}</td>
        {% endfor %}
    </tr>
    {% endfor %}
</table>

配套你提供的CSS样式即可实现预期的表格边框效果:

table,td{
  border: 1px solid black;
  padding: 1px;
}

补充说明

  • 如果你需要在单元格内显示last.xxx、primary.xxx的前缀,将<td>{{ value }}</td>分别改成<td>last.{{ value }}</td>和<td>primary.{{ value }}</td>即可
  • 如果两个子数组的字段数量不一致,你可以额外补全空的<td>元素保证表格列对齐

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 21:57:03