tipsy / j2html

Java to HTML generator. Enjoy typesafe HTML generation.
https://j2html.com/
Apache License 2.0
765 stars 136 forks source link

text methods should have an overloaded variant accepting a formatter #107

Closed uhafner closed 6 years ago

uhafner commented 6 years ago

I frequently use formatted strings to create text nodes or to supply properties (like href). It would be nice, if there would be an overloaded method that uses internally a formatter.

Current API:

rawHtml(getSomething() + " - " + getSomethingAgain());
a(getSomething() + " - " + getSomethingAgain()).withHref(getBaseUrl() + "/" + getRelUrl())

Expected API

rawHtml("%s: %s", getSomething(), getSomethingAgain());
a("%s: %s", getSomething(), getSomethingAgain()).withHref("%s/%s", getBaseUrl(), getRelUrl())

I.e., there need to be additional methods like

    public static ContainerTag a(String text) {
        return new ContainerTag("a").withText(text);
    }
    public static ContainerTag a(String text, Object... args) {
        return new ContainerTag("a").withText(text, args);
    }
tipsy commented 6 years ago

@uhafner is this just to avoid writing using String.format() ? It seem to be a bit of a special cases. Are you running into this a lot, or just for anchors?

There is already a join() method which you might find useful in some cases.

a(join(getSomething(), "-", getSomethingAgain()))

uhafner commented 6 years ago

The reason is to avoid String.format, yes. I thought it might be useful for others too. Maybe my use case is not typical. I also use join and String concatenation. But most times I prefer to use a String formatter, but this might be a personal preference. (E.g., on the one hand the Java Logger does support strings and formatted strings as message, on the other hand, Exception constructors actually not. So there is no real standard in Java anyway.)

Here is an example of my usage.

tipsy commented 6 years ago

There hasn't been any interest in this, so I'm going to close the issue and recommend that people use either join() or String.format() (you can statically import the method to make it less verbose).