Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use j2html without rendering everything

Tags:

java

html

j2html

I am converting my html rendering code to use j2html. Whilst I like the library it is not easy for me to convert all the code in one go so sometimes I may convert the outer html to use j2html but not able to convert the inner html to j2html at the same time. So I would like j2html to be able to accept text passed to it as already rendered, but it always re-renders it so

System.out.println(p("<b>the bridge</b>"));

returns

<p>&lt;b&gt;the bridge&lt;/b&gt;</p>

is there a way I get it to output

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

Full Test Case

import j2html.tags.Text;

import static j2html.TagCreator.b;
import static j2html.TagCreator.p;

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

}
like image 550
Paul Taylor Avatar asked Jun 20 '17 08:06

Paul Taylor


People also ask

Why did you make j2html?

You use a CSS framework which relies on a lot of copy pasting HTML from docs. You'll have to translate these snippets to j2html Why did you make this library? First: j2html is a Java HTML builder. It's not a template engine, and it doesn't want to compete with template engines.

How to create a basic HTML structure in j2html?

Creating a basic HTML structure in j2html is pretty similar to plain HTML. This Java code: html( head( title("Title"), link().withRel("stylesheet").withHref("/css/main.css") ), body( main(attrs("#main.content"), h1("Heading!") ) ) )

How to render a form in a header frame in j2html?

In j2html you can specify the context in which a view is rendered, and supply the rendering method with type safe parameters! If we want to insert our form in a header/footer frame, we simply create a MainView and make it take our view as an argument:

Why is the rendered HTML more verbose than the rendered Java?

The rendered HTML is more verbose: Imagine if you wanted labels in addition. The Java snippet would look almost identical: You could create a partial called passwordAndLabel () and nothing but the method name would change.


2 Answers

import static j2html.TagCreator.b;
import static j2html.TagCreator.p;
import static j2html.TagCreator.rawHtml;


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

}

Result:

<p><b>the bridge</b></p>
<p><b>the bridge</b></p>
like image 97
selten98 Avatar answered Oct 25 '22 21:10

selten98


In j2html 1.1.0 you can disable text-escaping by writing

Config.textEscaper = text -> text;

Be careful though..

like image 41
tipsy Avatar answered Oct 25 '22 20:10

tipsy