【问题标题】:Helper in handlebars printing HTML tags车把中的助手打印 HTML 标签
【发布时间】:2016-03-24 06:08:04
【问题描述】:

我有这个把手代码试图动态创建这个表

<tr>
    {{#each this}}
        {{#ifCond this }}
        {{/ifCond}}
    {{/each}}
</tr>

现在我有一个像这样定义的把手助手(在 res.render 中发送这个助手,就像这样)

'ifCond': function( state ) {
    if(state == "success") 
        return Spacebars.SafeString('<td class="tile-green">' + state + '</td>');
    else if( state == "failure")
        return Spacebars.SafeString('<td class="tile-red">' + state + '</td>');
    else if (state == "unknown"
        return Spacebars.SafeString('<td class="tile-orange">' + state + '</td>');

    else 
        return Spacebars.SafeString('<td>' + state + '</td>');
}

似乎没有工作。谁能帮我解决这个问题?

【问题讨论】:

  • 我不会使用 this 这是保留关键字。
  • 那么我如何将当前值传递给助手。当前值是“this”的值。
  • 如果this 是模板中可用的变量,那么它假定您正在传递像{ this: [ array of values or objects ] } 这样的对象。你能展示数据结构以及如何将它们传递给车把吗?

标签: node.js html-table handlebars.js helper


【解决方案1】:

下面是一个示例:https://jsfiddle.net/ChristopheThiry/L34f7rm2/

模板:

{{#each lines}}
<tr>
    {{#each columns as |column|}}
        {{#ifCond column}}
      {{/ifCond}}
    {{/each}}
</tr>
{{/each}}

助手:

  Handlebars.registerHelper('ifCond', function( column ) {
    if(column.state == "success") {
        return '<td class="tile-green">' + column.state + '</td>';
    } else if( column.state == "failure") {
       return '<td class="tile-red">' + column.state + '</td>';
    } else if (column.state == "unknown") {
        return '<td class="tile-orange">' + column.state + '</td>';
    } else {
        return '<td>' + column.state + '</td>';
    }
    });

数据:

{ "lines" : [
   { "columns" : [ { "state" : "STEP1" }, { "state" : "STEP2" }, { "state" : "STEP3" } ] },
   { "columns" : [ { "state" : "success" }, { "state" : "failure" }, { "state" : "unknown" } ] },
   { "columns" : [ { "state" : "success" }, { "state" : "success" }, { "state" : "unknown" } ] } 
           ] }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-02
    • 1970-01-01
    • 2016-01-10
    • 2013-02-05
    • 2019-01-05
    • 1970-01-01
    相关资源
    最近更新 更多