项目首页:http://mustache.github.com/
项目文档:http://mustache.github.com/mustache.5.html
Demo: http://mustache.github.com/#demo
简介:
Mustache 是一个 Logic-less templates,原本是基于javascript 实现的模板引擎,类似于 freemark和valicity ,但是比freemark和valicity更加轻量级更加容易使用,经过拓展目前支持javascript,java,.NET,PHP,C++等多种平台下开发!
Mustache.java开发
从http://jmustache.googlecode.com/svn位置检出mustache.java项目代码
将com.samskivert.mustache包下三个.java文件拷贝到项目目录下
新建TestMustache.java文件,拷贝如下代码:
package cn.mustache.test;
import java.util.HashMap;
import java.util.Map;
import com.samskivert.mustache.Mustache;
public class TestMustache {
/**
* Last Modification Time: 2011-6-27
*
* @param args
*/
public static void main(String[] args) {
//前面加#号的话,如果{{taxed_value}}也是会显示出来的
String templete = "Hello {{name}} \n" +
"You have just won ${{value}}! \n" +
"{{#in_ca}} " +
"Well, ${{taxed_value}}, after taxes. \n" +
"{{/in_ca}} ";
Map<String, Object> ctx = new HashMap<String, Object>();
ctx.put("name", "Chris");
ctx.put("value", "10000");
ctx.put("taxed_value", "10000 - (10000 * 0.4)");
ctx.put("in_ca", "true");
String result = Mustache.compiler().compile(templete).execute(ctx);
System.out.println(result);
}
}
输出:
Hello Chris
You have just won $10000!
Well, $10000 - (10000 * 0.4), after taxes.
解析:
templete为输出内容的模板,将map类型的ctx填充到templete中,经过编译和执行,便会按照模板生成result
顺便介绍一下基于javascript的开发:
从https://github.com/janl/mustache.js上download 下mustache.js文件
在项目下建js文件夹将mustache.js拷入
新建index.html文件,并将如下代码拷入:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="js/mustache.js""></script>
<title>test mustache</title>
</head>
<body>
<script language="javascript">
var data, template, html;
data = {
name : "Some Tuts+ Sites",
sites: ["Nettuts+", "Psdtuts+", "Mobiletuts+"],
url : function () {
return function (text, render) {
text = render(text);
var url = text.trim().toLowerCase().split('tuts+')[0] + '.tutsplus.com';
return '<a href="' + url + '">' + text + '</a>';
}
}
};
template = "<h1> {{name}} </h1>" +
"<ul> {{#sites}}" +
"<li> {{#url}} {{.}} {{/url}} </li>" +
"{{/sites}} </ul>" ;
html = Mustache.to_html(template, data);
document.write(html);
window.alert(html);
</script>
</body>
</html>