| 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/ 本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接,否則保留追究法律責任的權利。 |

