简体   繁体   English

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

[英]Handlebars Template rendering template as text

I created a helper in Handlebars to help with logic, but my template parses the returned html as text rather than html. 我在Handlebars中创建了一个帮助逻辑的帮助器,但是我的模板将返回的html解析为文本而不是html。

I have a quiz results page that is rendered after the quiz is completed: 我有一个测验结果页面,在测验完成后呈现:

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

For each of the rounds, I use a helper to determine which template to render a round's result: 对于每一轮,我使用一个帮助器来确定渲染圆形结果的模板:

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

Here is a template that describes a correct round (let's take say it rendered the #round-end-correct template): 这是一个描述正确回合的模板(让我们假设它呈现了#round-end-correct模板):

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

Here is what gets rendered: 以下是渲染的内容:

<div></div>

Not as HTML, but as text. 不是HTML,而是文本。 How do I get it to actually render the HTML as HTML, rather than text? 我如何让它实际将HTML呈现为HTML而不是文本?

I assume that unescaping in Handlebars works the same as in vanilla Mustache. 我假设Handlebars中的unescaping与vanilla Mustache中的相同。 In that case use triple mustaches to unescape html, i,e: {{{unescapedhtml}}} , like: 在这种情况下,使用三重胡须来unescape html,i,e: {{{unescapedhtml}}} ,如:

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

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

Geert-Jan's answers is correct but just for reference you can also set the result to "safe" directly inside the helper (code from handlebars.js wiki) 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); 
});

With that you can use regular double handlebars {{ }} and handlebars won't escape your expression. 有了这个,你可以使用常规的双把手{{}},并且把手不会逃脱你的表达。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM