| ylbtech-Template-TModJS:使用tmodjs |
| 1.返回顶部 |
1、
1、安装
npm install -g tmodjs
2、配置

我的模板都放在tpl文件夹中,htmls用于存放模板页面,每一个后缀名都是.html,而build用于存放编译后输出的模板js。
如果不设置type,默认会将所有的模板编译合并为 template.js ,而如果设置了type,就会单独生成对应js文件。

运行后htmls文件夹下会生成一个package.json文件。
3、模板语法
{{each Data as value index}}
<tr>
<td>{{value.ID}}</td>
<td>{{value.Client}}</td>
<td>{{value.ClientType | geterrtype}}</td>
<td>{{value.ErrCode}}</td>
<td>{{value.SqlString}}</td>
<td class="w70">{{value.CreateDate}</td>
<td>{{value.CreateTime}}</td>
</tr>
{{/each}}
{{content}}输出内容
{{#content}}不编码输出内容
if语句:
{{if admin}}
<p>admin</p>
{{else if code > 0}}
<p>master</p>
{{else}}
<p>error!</p>
{{/if}}
遍历:
{{each list as value index}}
<li>{{index}} - {{value.user}}</li>
{{/each}}
或者
{{each list}}
<li>{{$index}} - {{$value.user}}</li>
{{/each}}
注:使用辅助方法时{{value.ClientType | geterrtype}}中 | 两边的空格不能省略。
4、使用模板
4.1 type为默认时:
var template = require('/tpl/build/template.js');
var html = template('dblog', data);
$('#J_SearchResults').html(html);
4.2 type为非默认时,拿seajs举例:
var render = require('/tpl/build/dblog');
var html = render(data);
$('#J_SearchResults').html(html);
5、使用辅助方法
package.json中有一个helpers配置项
{
"name": "template",
"version": "1.0.0",
"dependencies": {
"tmodjs": "1.0.1"
},
"tmodjs-config": {
"output": "../build",
"charset": "utf-8",
"syntax": "simple",
"helpers": null,
"escape": true,
"compress": true,
"type": "default",
"runtime": "template.js",
"combo": true,
"minify": true,
"cache": true
}
}
我们可以在模板目录新建一个 config/template-helper.js 文件,然后编辑 package.json 设置"helpers": "./config/template-helper.js"。
里面的代码类似:
template.helper("geterrtype", function(n) {
// return xxx;
});
template.helper("dataformat", function(n,format) {
// return xxx;
});
但是我在迁移模板的时候发现template-helper.js中不能获取外部的变量也不能引入外部的js,不然会报错。

但是如果辅助方法不是在这里设置,而是在普通的js中就可以用:
var template = require('/tpl/build/template.js');
template.helper("geterrtype", function(n) {
return common._getErrType(n);
});
var html = template('dblog', data);
$('#J_SearchResults').html(html);
下面这种也可以= =虽然感觉怪怪的:
var template=require('/tpl/build/template');
template.helper("geterrtype", function(n) {
return common._getErrType(n);
});
var render = require('/tpl/build/dblog');
var html = render(data);
$('#J_SearchResults').html(html);
2、
| 2.返回顶部 |
| 3.返回顶部 |
| 4.返回顶部 |
| 5.返回顶部 |
| 6.返回顶部 |
| 作者:ylbtech 出处:http://ylbtech.cnblogs.com/ 本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。 |
