把手模板渲染模板作为文本

egi*_*dra 52 javascript template-engine mustache handlebars.js

我在Handlebars中创建了一个帮助逻辑的帮助器,但我的模板将返回的html解析为文本而不是html.

我有一个测验结果页面,在测验完成后呈现:

  <script id="quiz-result" type="text/x-handlebars-template">
        {{#each rounds}}
          {{round_end_result}}
        {{/each}}
        <div class="clear"></div>
  </script>
Run Code Online (Sandbox Code Playgroud)

对于每一轮,我使用一个帮助器来确定渲染圆形结果的模板:

  Handlebars.registerHelper("round_end_result", function() {
    if (this.correct) {
      var source = '';
      if (this.guess == this.correct) {
        console.log("correct guess");
        var source = $("#round-end-correct").html();
      } else {
        var source = $("#round-end-wrong").html();
      }
      var template = Handlebars.compile(source);
      var context = this;
      var html = template(context);
      console.log(html);
      return html;
    } else {
      console.log("tie");
    }
  });
Run Code Online (Sandbox Code Playgroud)

这是一个描述正确回合的模板(让我们假设它呈现了#round-end-correct模板):

  <script id="round-end-correct" type="text/x-handlebars-template">
        <div></div>
  </script>
Run Code Online (Sandbox Code Playgroud)

以下是渲染的内容:

<div></div>
Run Code Online (Sandbox Code Playgroud)

不是HTML,而是文本.我如何让它实际将HTML呈现为HTML而不是文本?

Gee*_*Jan 148

我假设Handlebars中的unescaping与vanilla Mustache中的相同.在那种情况下使用三重胡须来unescape html,我,e : {{{unescapedhtml}}},喜欢:

<script id="quiz-result" type="text/x-handlebars-template">
    {{#each rounds}}
      {{{round_end_result}}}
    {{/each}}
    <div class="clear"></div>
Run Code Online (Sandbox Code Playgroud)

请参阅:http: //mustache.github.com/mustache.5.html


Pet*_*chl 19

Geert-Jan的答案是正确的,但仅供参考,您也可以直接在帮助程序中将结果设置为"安全"(来自handlebars.js wiki的代码)

Handlebars.registerHelper('foo', function(text, url) { 
  text = Handlebars.Utils.escapeExpression(text);
  url = Handlebars.Utils.escapeExpression(url); 
  var result = '<a href="' + url + '">' + text + '</a>'; 
  return new Handlebars.SafeString(result); 
});
Run Code Online (Sandbox Code Playgroud)

有了这个,你可以使用常规的双把手{{}},并且把手不会逃脱你的表达.