lodash是从underscore分支的一个项目,之前我写了一篇JS模板工具underscore.template的简单用法,lodash跟underscore很相似,这也简单介绍一下lodash的template方法。
先把underscore的文章中用过的代码贴过来,把underscore的js文件换成lodash的js,其他一字不改,然后我们试试:
- -
_.each(datas, function (item) { %>
- -
} %>
var datas = [
{
film: '电影名称1',
url: 'http://www.baidu.com',
director: '导演名称1'
},
{
film: '电影名称2',
url: 'http://www.baidu.com',
director: '导演名称2'
},
{
film: '电影名称3',
url: 'http://www.baidu.com',
director: '导演名称4'
},
{
film: '电影名称4',
url: 'http://www.baidu.com',
director: '导演名称4'
},
];
$('#example1').html( _.template($('#tpl1').html(), datas) );
$('#example2').html( _.template($('#tpl2').html(), datas) );
可以看到,正常打印了模板。
经过我的测试,lodash的运行效率比underscore的效率高一点点,这也符合业界对这两个库的评价,就是lodash比underscore高明一点点,所以以后尽量用lodash做模板引擎就好了。
用法可以参考中文文档,主要用法有两种:
第一种:
_.template('hello !')({ 'user': 'fred' })
第二种:
_.template('hello !', { 'user': 'fred' })
经过我的测试,第一种更快,所以大家以后尽量用第一种,而且官方示例全部是第一种写法。
掌握这一种写法,再掌握各种分隔符,就足够应对日常应用。
上面例子是以json直接量作为数据源,现在假设我们有一个json文件,我们应该怎么把数据插入到模板中?
先写HTML代码:
也就是说,最外层div有一个data-api="xxoourl",用于指定源,里面是一个,其中有两个循环,一个是循环daily,另一个是循环weekly。那么我们怎么组织这个json源?
在对象中设两个键,分别叫daily和weekly,每个键的值都是数组,数组的每个元素都是对象,每个对象就是一组数据。
{
"daily": [
{
"rankWord": "11.8k",
"avatarUrl": "https://sfault-avatar.b0.upaiyun.com/427/102/4271029182-55b7a3c57d25b_big64",
"name": "eechen",
"url": "/u/eechen",
"incr": "79"
},
...
],
"weekly": [
{
"rankWord": "1k",
"avatarUrl": "https://sfault-avatar.b0.upaiyun.com/726/291/726291045-57fdead795d4e_big64",
"name": "orangexc",
"url": "/u/orange_1995",
"incr": "198"
},
...
]
}
然后是js代码:
var timestamp = new Date().getTime();
$('[data-api]').each(function() {
var $_self = $(this);
$.get('/app/dev' + $_self.attr('data-api') + '?v=' + timestamp, function(data) {
$_self.html( _.template($_self.find('script').html())(data) );
}, 'json');
});
这段的意思是遍历所有api容器,然后拉取源,将源解析成HTML代码,然后替换容器内的数据即可。这样也抹掉了模板。如果你不想抹掉模板,将$_self.html()改成$_self.append()即可。
总结:我们只要有容器、有源、有模板,就可以构建出一套HTML代码。