使用Handlebars进行条件CSS

时间:2017-01-29 20:55:43

标签: handlebars.js

在下面的代码片段中,我希望第一行包含类new-entry和第c行以使类升级,但两者都没有。

我确定这是一个愚蠢的错误,但我看不到它

Handlebars.registerHelper("newEntry", function() {
    return this.newEntry ? 'class="new-entry"' : '';
});

Handlebars.registerHelper("movingUp", function() {
    return this.movingUp ? 'class="moving-up"' : '';
});

var source = document.getElementById('leaderboard-template').innerHTML; 
var template = Handlebars.compile(source); 
var outlet = document.getElementById('outlet');

  outlet.innerHTML = template({leaders: [
    {name: 'a', signature_count: 10, newEntry: true},
    {name: 'b', signature_count: 8},
    {name: 'c', signature_count: 6, movingUp: false},
  ]});
.new-entry {
  background-color:red;
}
.moving-up {
  color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.6/handlebars.min.js"></script>

<script id="leaderboard-template" type="text/x-handlebars-template"> 
  <table>
      <thead> 
          <th>Constituency</th> 
          <th>Votes</th> 
      </thead> 
      <tbody> 
          {{#leaders}} 
          <tr {{newEntry}}> 
              <td>{{name}}</td> 
              <td><span {{movingUp}}>{{signature_count}}</span></td> 
          </tr> 
          {{/leaders}} 
      </tbody> 
  </table> 
</script>

<div id="outlet"></div>

1 个答案:

答案 0 :(得分:1)

Handlebar将助手的返回值转换为HTML转义字符串。如果您不想要,请使用Handlebars.SafeString这样的内容:

Handlebars.registerHelper("newEntry", function() {
    return new Handlebars.SafeString( this.newEntry ? 'class="new-entry"' : '' );
});

Handlebars.registerHelper("movingUp", function() {
    return new Handlebars.SafeString( this.movingUp ? 'class="moving-up"' : '' );
});