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

如何使用j2html让方法返回多个标签以适配表格布局?

Cleanly Reusing Table Cells in j2html Without Iterable Complexity

Coming from a Java background, using tables for structured form layout feels totally intuitive—so I get exactly why you want to stick with that pattern while adding flexibility for extra elements like buttons. The hassle of having to use each() when returning a List<Tag> is a real pain, but j2html has a perfect solution for this.

The Fix: Use fragment() to Group Elements Without Extra Markup

j2html provides a fragment() utility that lets you wrap multiple DomContent instances (like your <td> tags) into a single DomContent object—without generating any extra HTML container tags (critical here, since <tr> can only contain <td> elements). This lets you return a reusable group of cells that plays seamlessly with j2html's builder syntax.

Modified Method Code

import j2html.tags.DomContent;
import static j2html.TagCreator.*;

public DomContent addInputTextTds(UserOption userOption, String value, String className) {
    return fragment(
        td(label(userOption.getLabelMsg())
            .withTitle(userOption.getTooltipMsg())),
        td(input()
            .withType(Html.TEXT)
            .withName(userOption.getOption()).withValue(value)
            .withClass(className)
        )
    );
}

Simplified Call Syntax

Now you can directly pass the fragment alongside your extra button <td> to the tr() builder—no messy each() required:

tr(
    addInputTextTds(UserOption.LICENSE_EMAIL, licenseEmail, LICENSE_INPUTFIELD_CLASS),
    td(button("Manage").withClass("action-btn")) // Your extra button cell
)

Bonus: Keep Both Patterns for Flexibility

If you still need the original "full row" behavior for some cases, just keep your original addInputTextTr() method alongside this new one. That way you can pick the right approach based on whether you need to extend the row or not.

This approach keeps your code DRY, maintains valid HTML structure, and eliminates the Iterable/Stream complexity you were dealing with.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:24:06