您应该看到约翰Resiq这篇博客文章:JavaScript Micro-Templating
它有一个简单的微模板代码,你可以重新使用。它是这样的:
// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
var cache = {};
this.tmpl = function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');");
// Provide some basic currying to the user
return data ? fn(data) : fn;
};
})();
所以,你的模板将在标记:
<script type="text/html" id="item_tmpl">
<div id="<%=id%>" class="<%=(i % 2 == 1 ? " even" : "")%>">
<div class="grid_1 alpha right">
<img class="righted" src="<%=profile_image_url%>"/>
</div>
<div class="grid_6 omega contents">
<p><b><a href="/<%=from_user%>"><%=from_user%></a>:</b> <%=text%></p>
</div>
</div>
</script>
要使用它:
var results = document.getElementById("results");
results.innerHTML = tmpl("item_tmpl", dataObject);
需要明确的是 - 上面的例子是取自博客文章,并且是不是我的代码。点击链接了解更多信息。
你有没有试过JS框架[jQuery](http://jquery.com/)? – NullUserException 2010-08-19 17:21:42
@NullUserException是的,jQuery很好,但它自己似乎没有提供解决方案,只是使它更容易。我相信性能也会受到影响(例如,在手机浏览器上很受欢迎)。 @ Dave的建议使用JQuery,并且更接近。我很困惑,不应该有JSON的等效XSLT转换吗? – MandoMando 2010-08-19 17:54:20
这里似乎有一个很好的讨论:http://ajaxpatterns.org/Browser-Side_Templating – MandoMando 2010-08-19 18:43:43