使用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
相关产品推荐
相关产品推荐

