Search code examples
javahtmlj2html

How do I render text containing html with j2html java to html lib


Been using j2html to create html from Java, working well but I don't understand how to use when I want something like this

<p>The fox ran over the <b>Bridge</b> in the forest</p>

If I do

import static j2html.TagCreator.*;

    public class HtmlTest
    {
         public static void main(String[] args)
         {
            System.out.println(p("The fox ran over the " + b(" the bridge") + "in the forest"));
         }

    }

I get

<p>The fox ran over the &lt;b&gt;the bridge&lt;/b&gt; in the forest</p>

i.e it treats bold as just text.

Note simply doing

import static j2html.TagCreator.*;

public class HtmlTest
{
     public static void main(String[] args)
     {
        System.out.println(p(b("the bridge")));
     }

}

does render properly giving

<p><b>the bridge</b></p>

Solution

  • I've never used j2html, but looking at the example, if I'm not wrong, I guess the syntax should be:

    p("The fox ran over the ", b(" the bridge"), "in the forest")
    
    Sorry my company environment doesn't allow me to download Eclipse etc to test.. .

    Update: Above was wrong. But I've found a way - although it is rather complex:

    p("The fox ran over the ").with((DomContent)b("the bridge")).withText(" in the forest")
    

    Output:

    <p>The fox ran over the <b>the bridge</b> in the forest</p>
    

    (DomContent) can be removed but I retained for clarify. I guess the logic is that if anything added as text would be escaped, so the only way to make it work is to add the DomContent or ContainerTag instead.

    Update 2: "Better" way found!

    p(new Text("The fox ran over the "), b("the bridge"), new Text(" in the forest"))
    

    or with a "helper"

    import static j2html.TagCreator.*;
    import j2html.tags.Text;
    
    public class Test {
    
        private static Text $(String str) {
            return new Text(str);
        }
    
        public static void main(String[] args) {
            System.out.println(p($("The fox ran over the "), b("the bridge"), $(" in the forest")));
        }
    
    }