Improvement: invisible parent tag
See original GitHub issueI came across a situation in which I need something like an invisible parent to generate something like this:
<ul>
<li>First</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>Last</li>
</ul>
This structure is often used in generating paginating bars. The part from 5 to 7 is generated.
In similar situations, you would an extra div:
ul().with(
li("First"),
div().with(
numbers.stream().map(number ->
li(number.toString())
).collect(Collectors.toList())
),
li("Last")
)
But a div directly inside a UL-element is unwanted.
Another option (without creating new classes):
ul().with(
li("First"),
unsafeHtml(
numbers.stream().map(number ->
li(number.toString()).render()
).collect(Collectors.joining(""))
),
li("Last")
)
But the use of unsafeHtml(), render() and joining(“”) doesn’t feel very nice.
Another option would to to create something like an invisible parent tag, a tag that doesn’t show its own element, only its children:
ul().with(
li("First"),
group(
numbers.stream().map(number ->
li(number.toString())
).collect(Collectors.toList())
),
li("Last")
)
This can further be improved with a custom java.util.stream.Collector that internally used the group(), so that group() doesn’t have to be exposed:
ul().with(
li("First"),
numbers.stream().map(number ->
li(number.toString())
).collect(domContentCollector()),
li("Last")
)
This last one looks very nice imo, with the domContentCollector().
But solution does require Java 1.8 instead of 1.7.
Code: https://github.com/jtdev/j2html/commit/bf7e3ac5bd0aa2de256c91070709ad69d9220ddb (Not fully sure whether DomContentCollector is implemented completely correct.)
Issue Analytics
- State:
- Created 7 years ago
- Comments:8 (5 by maintainers)
Top GitHub Comments
@kosiakk Using variables breaks the readability of the html and fluent api imo.
Mixing DomContent with Lists gives a loss of type safety.
And the
stream()
with.collect(domContentCollector())
approach is a bit verbose, although flexible.each(collection, mapper)
andfilter()
are a nice short solutions although not sure if they fit all use cases.each(stream, mapper)
would fit more use cases, although slightly more verbose.About
if
, I created an issue for it here: https://github.com/tipsy/j2html/issues/21if
is maybe even more difficult thaneach
in terms of discovering a nice api.Btw, speaking about Kotlin, Scala also has a HTML builder: Scalatags: http://www.lihaoyi.com/scalatags/ In Clojure (also a JVM language), they have Hiccup: https://github.com/weavejester/hiccup
Nice work! I was playing around a little, and I really think the stream API is too verbose. I created an alternative suggestion:
Made possible by a helper like this:
But it won’t really work if you need to do something like
employee.getName()
. Feels like it should be possible, but I’m still pretty new to functions/lambdas/generics/wildcards.