在把手的标签中逃脱花括号

时间:2018-04-23 21:36:41

标签: javascript handlebars.js

我有把手打印出标签列表的车把代码。

This values are:

{{#each theObj.Options}} 

{{#if @last}}
{{this.valueLabel}}
{/if}}

{{#unless @last}}
{{this.valueLabel}, 
{{/unless}}

{{/each}}.

</p>{{/compare}}

valueLabels是:

Value A
 Value B
 {Test}

车把代码打印出来:

The values are: Value A, Value B, .

我需要打印出最后一个{Test}。我怎么做?打印输出应为:

The values are: Value A, Value B, {Test}.

感谢。

1 个答案:

答案 0 :(得分:0)

快速编写代码笔似乎可以产生预期的结果。这有三个警告:

  1. 我添加了额外的&#39; {&#39;以前的第7行HTML:&#39; {/ if}}&#39;。
  2. 我删除了结束&#39; {{/ compare}}&#39;标记,因为您的示例中没有包含任何开头。
  3. 我创建了一个对象&#39; theObj&#39;猜测应该包含哪些内容的合理例子。
  4. 你能否澄清一下'theObj&#39;对象所以我们可以解决这个问题吗?

    <强> HTML

    <div id="app"></div>
    
    <script id="entry-template" type="text/x-handlebars-template">
      This values are:
    
      {{#each theObj.Options}} 
    
      {{#if @last}}
        {{this.valueLabel}}
      {{/if}}
    
      {{#unless @last}}
        {{this.valueLabel}}, 
      {{/unless}}
    
      {{/each}}.
    </script>
    

    <强>的JavaScript

    var theObj = {
      Options: [{valueLabel: 'Value A'}, {valueLabel: 'Value B'}, {valueLabel: '{Test}'}]
    };
    
    var source   = document.getElementById('entry-template').innerHTML;
    var template = Handlebars.compile(source);
    
    var context = {theObj: theObj};
    var html    = template(context);
    
    document.getElementById('app').innerHTML = html;
    
    console.log(html);
    

    您可以在此处查看代码笔示例:

    请参阅Escaping curly braces in a label in handlebars上的Nicholas Lawrence(@nicholaslawrencestudio)的笔CodePen