使用mustache.js行条带化和第一个/最后一个类 [英] row striping and first/last classes with mustache.js

查看:72
本文介绍了使用mustache.js行条带化和第一个/最后一个类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,人们希望将列表中的第一个和/或最后一个项目与其他项目区别对待。有没有办法用胡子做到这一点?行条纹怎么样?

Frequently one wants to treat the first and/or last items in a list differently from the others. is there a way to do that using mustache? what about row striping?

(显然,在模板处理完毕后,人们总是可以使用jquery或其他什么来应用css类,或者其他什么,但我想知道更多的东西在模板级别。)

(Obviously, one could always use jquery or whatever to apply a css class after the template has been processed, or whatever, but I'm wondering about something more at the template level.)

推荐答案

小胡子很轻,所以AFAIK,它没有提供这个功能。

Mustache is very light, so AFAIK, it does not provide that feature.

您可以使用类似的东西来获得偶数/奇数类:

You can use something like that, to get even/odd class:

var view = {
  arr: ['one', 'two', 'three'],
  clazz: function() {
    return _counter++ % 2 == 0 ? 'even' : 'odd';
  }
};

var template = '{{#arr}}<span class="{{clazz}}">{{.}}</span>{{/arr}}';
Mustache.to_html(template, view);

或者首先预处理数据,类似:

Or preprocess the data first, something like that:

function preprocessArrayWithFirstLastClass(src) {
  var clazz;
  for (var i = 0; i < src.length; i++) {
    clazz = i % 2 == 0 ? 'even' : 'odd';
    if (i == 0) clazz += ' first';
    if (i == src.length - 1) clazz += ' last';
    src[i].clazz = clazz;
  }
}

var view = {
  arr: preprocessArrayWithFirstLastClass([{name: 'one'}, {name: 'two'}, {name: 'three'}])
};

var template = '{{#arr}}<span class="{{clazz}}">{{name}}</span>{{/arr}}';
Mustache.to_html(template, view);

这篇关于使用mustache.js行条带化和第一个/最后一个类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆