1

How do I make use of j2htmls each method to add elements of a collection ?

They give an example on 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())
            )
        )
    )
)

But they don't define what employees or employee actually are.

In my case I want add series of Counter elements to a div (each with label) but I cannot see how to do it, so for now I am only using j2html for each individual counter and then wrapping it with hardcoded tag.

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");
4

1 回答 1

1

Okay so what I wasn't grasping in the example was employees is the collection variable and employee is arbitary, it is simply the local variable assigned to the loop and can be anything you want.

So now have it working.

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())
                        )
                )
        )
    )
)));    
于 2017-12-12T15:49:06.477 回答