당신은 존 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);
것은 명확하게하기 위해 - 위의 예제가에서 찍은 블로그 게시물은 이 아니며 내 코드입니다. 자세한 정보는 링크를 클릭하십시오.
[jQuery] (http://jquery.com/)와 같은 JS 프레임 워크를 사용해 보셨나요? – NullUserException
@NullUserException 예, jQuery는 훌륭하지만 솔루션 자체를 제공하지 않는 것 같아서 더 쉽게 사용할 수 있습니다. 실적이 저조합니다 (예 : 모바일 브라우저의 경우). @ Dave의 제안은 JQuery를 사용하며 더 가깝습니다. 나는 당황 스럽다. 거기에 JSON을위한 XSLT 변환이 없을까? – MandoMando
여기에 좋은 토론이있는 것 같습니다 : http://ajaxpatterns.org/Browser-Side_Templating – MandoMando