jQuery 内部的 Mustache 模板字符串呈现为 HTML

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16800496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:49:45  来源:igfitidea点击:

Mustache template string inside render as HTML

javascriptjqueryhtmlmustache

提问by Snow_Mac

I am using Mustache to render templates.

我正在使用 Mustache 来渲染模板。

I have this json object:

我有这个 json 对象:

  {
    title: "Foo bar", 
    content: "<p> Html here </p>", 
    footer: "footer content here"
  }

I have a Mustache template like:

我有一个 Mustache 模板,例如:

  <div id="box">
    <div id="title"> {{title}} </div> 
    <div id="content"> {{content}} </div> 
    <div id="footer"> {{footer}} </div> 
  </div>

My problem is that the html within the variable content is not getting rendered but instead is just getting printed to the screen.

我的问题是变量内容中的 html 没有被渲染,而是被打印到屏幕上。

I see (in non-view source window): <p> Html here </p>, where I would only want to see that if I viewed the page source.

我看到(在非查看源窗口中): <p> Html here </p>,如果我查看页面源,我只想看到它。

How can I fix such that when I pass in a string to a mustache template the HTML inside gets rendered? I am calling mustache.render(templates.all,data); as my call to mustache.

我该如何解决,当我将字符串传递给 mustache 模板时,内部的 HTML 会被渲染?我打电话给 mustache.render(templates.all,data); 作为我对小胡子的呼唤。

回答by Amy

From the Mustache documentation:

来自Mustache 文档

All variables are HTML escaped by default. If you want to return unescaped HTML, use the triple mustache: {{{name}}}.

默认情况下,所有变量都是 HTML 转义的。如果要返回未转义的 HTML,请使用三重胡子:{{{name}}}。

So you just have to use eg.{{{content}}}in your template:

所以你只需要使用例如。{{{content}}}在您的模板中:

  <div id="box">
    <div id="title"> {{title}} </div> 
    <div id="content"> {{{content}}} </div> 
    <div id="footer"> {{footer}} </div> 
  </div>

回答by Venkatesh K

You can render easily by using java code.

您可以使用 java 代码轻松渲染。

Map<String,String> vars =new HashMap<>();
vars.put("title","Foo bar");
vars.put("content","Html here");
vars.put("footer","footer");
String renderedString = Mustache.compiler().compile(yourBodyTemplate()).execute(vars);

Write the renderedstring to a html file. Thats it.

将渲染的字符串写入 html 文件。就是这样。