【问题标题】:Handlebars Template rendering template as textHandlebars Template 将模板渲染为文本
【发布时间】:2011-11-02 08:46:40
【问题描述】:

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

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

  <script id="quiz-result" type="text/x-handlebars-template">
        {{#each rounds}}
          {{round_end_result}}
        {{/each}}
        <div class="clear"></div>
  </script>

对于每一轮,我使用一个助手来确定哪个模板来呈现一个轮的结果:

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

这是一个描述正确回合的模板(假设它渲染了#round-end-correct 模板):

  <script id="round-end-correct" type="text/x-handlebars-template">
        <div></div>
  </script>

这是渲染的内容:

<div></div>

不是 HTML,而是文本。如何让它真正将 HTML 呈现为 HTML,而不是文本?

【问题讨论】:

    标签: javascript template-engine mustache handlebars.js


    【解决方案1】:

    我认为 Handlebars 中的取消转义与 vanilla Mustache 中的工作方式相同。 在这种情况下,使用三重胡须来取消转义 html,即:{{{unescapedhtml}}},例如:

    <script id="quiz-result" type="text/x-handlebars-template">
        {{#each rounds}}
          {{{round_end_result}}}
        {{/each}}
        <div class="clear"></div>
    

    参考见: http://mustache.github.com/mustache.5.html

    【讨论】:

    • 在使用带有 2 个参数的 registerBoundHelper 时,此方法对我不起作用。但是“返回新的 Handlebars.SafeString(result);”为我工作。
    【解决方案2】:

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

    这样你就可以使用常规的双把手 {{ }} 并且把手不会逃避你的表达。

    【讨论】:

      猜你喜欢
      • 2012-09-08
      • 2013-01-22
      • 2016-12-12
      • 2013-01-27
      • 1970-01-01
      • 2016-06-24
      • 1970-01-01
      • 2014-07-05
      • 1970-01-01
      相关资源
      最近更新 更多