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

使用j2html生成指定表格HTML遇嵌套问题求解决方案

用j2html生成目标表格的实现代码

我完全懂你这种嵌套写法绕晕的感觉——j2html的链式API一开始确实需要适应下。直接给你对应目标HTML的实现代码,再拆解下每部分的对应关系:

import static j2html.TagCreator.*;

public class TableExample {
    public static void main(String[] args) {
        String tableHtml = table().withAttr("border", "0")
            .with(tr(
                td().withStyle("vertical-align: top").with(b("Some Info:")),
                td().withStyle("vertical-align: top").with(p("\"some fetched info\""))
            ))
            .render();
        
        System.out.println(tableHtml);
    }
}

代码对应说明:

  • table().withAttr("border", "0"):对应目标HTML里的<table border=0>;
  • tr(...):包裹两个<td>元素,对应表格里的一行;
  • 每个td()通过withStyle("vertical-align: top")设置单元格的垂直对齐样式,和目标里的style="vertical-align: top"对应;
  • 第一个单元格里的b("Some Info:")对应<b>Some Info:</b>,第二个单元格的p("\"some fetched info\"")对应<p>"some fetched info"</p>(注意Java字符串里双引号需要转义);
  • 最后调用render()方法就能把j2html的元素结构转为你需要的HTML字符串。

这样写出来的代码运行后,就能生成你指定的目标HTML啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:58:45