我如何使用 j2html each 方法

How do I use j2html each method

如何使用 j2htmls each 方法添加集合元素?

他们举了一个例子 https://j2html.com/examples.html

// each() lets you iterate through a collection and returns the generated HTML
// as a DomContent object, meaning you can add siblings, which is not possible
// using the stream api in the previous example
body(
    div(attrs("#employees"),
        p("Some sibling element"),
        each(employees, employee ->
            div(attrs(".employee"),
                h2(employee.getName()),
                img().withSrc(employee.getImgPath()),
                p(employee.getTitle())
            )
        )
    )
)

但他们没有定义 employeesemployee 实际上是什么。

在我的例子中,我想将一系列 Counter 元素添加到 div(每个元素都有标签),但我看不到如何去做,所以现在我只使用 j2html 为每个 individual 计数器,然后用硬编码标签包装它。

sb.append("<div>\n");
for(Map.Entry<Integer, Counter> next:fsc.getCounters().entrySet())
{
    sb.append(label(next.getValue().getText()).attr("for","pb"+next.getKey().intValue()));
    sb.append(render(progress()
            .withId("pb"+next.getKey().intValue())
            .attr("value", next.getValue().getCounter().intValue())
            .attr("max", "100")));
    sb.append(rendern(br()));
}
sb.append("</div>\n");

好吧,我在示例中没有掌握的是 employees 是集合变量,而 employee 是任意的,它很简单分配给循环的局部变量,可以是任何你想要的。

所以现在开始工作了。

sb.append(rendern(table(each(fsc.getCounters().entrySet(), next ->
        tr(
                td(
                        label(next.getValue().getText())
                                .attr(FOR,PB_PREFIX+next.getKey().intValue())),
                td(
                        iffElse(next.getValue().getBar().isIndeterminate(),
                                progress()
                                        .withId(PB_PREFIX+next.getKey().intValue()),
                                progress()
                                        .withId(PB_PREFIX+next.getKey().intValue())
                                        .attr(VALUE, next.getValue().getCounter().intValue())
                                        .attr(MAX, next.getValue().getBar().getMaximum())
                        )
                )
        )
    )
)));