2017-06-16 60 views
0

到HTML中使用j2html去过创建Java的HTML,工作很好,但我不明白如何时,我想是这样的如何呈现文本包含HTML与j2html java的LIB

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

如果使用我做

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

    } 

我得到

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

即它把大胆只是文本。

注意简单地做

import static j2html.TagCreator.*; 

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

} 

不正确呈现给

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

回答

1

我从来没有用过j2html,但看example,如果我没有错,我猜的语法应该是:

p("The fox ran over the ", b(" the bridge"), "in the forest") 
对不起,我的公司环境不允许我下载Eclip se等来测试.. 。

更新:上面错了。但我已经找到一种方法 - 虽然这是相当复杂的:

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

输出:

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

(DomContent)可以删除,但我保留澄清。我猜想逻辑是,如果任何以文本方式添加的内容都会被转义出来,那么唯一的办法就是添加DomContentContainerTag

更新2:“更好”的方式找到!

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

或一个 “助手”

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

} 
+0

大,三江源 –

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

可以写成

p(join("The fox ran over the", b("Bridge"), "in the forest") 
+0

是参加由j2html提供的功能,无法找到它? –

+0

是的,https://github.com/tipsy/j2html/blob/f87f9d864716809da2f6e61d946e9c12259d8e67/src/main/java/j2html/TagCreator.java#L71-L81 – tipsy