PHPだとSmartyなどのテンプレートエンジンを利用したりするが、同様にJavaScriptでクライアントサイドでテンプレートに変数を流しこむ様な実装を行うことができるライブラリを探したところ、jQueryのtemplatesプラグインで実現できる様なので使ってみた。
Templates – jQuery API
A template contains markup with binding expressions. The template is applied to data objects or arrays, and rendered into the HTML DOM.
api.jquery.com51 Users56 PocketsPage not found | jQuery API Documentationhttp://api.jquery.com/category/plugins/templates/
こういうのは、サンプルを見たほうが早いのでサンプルを以下に掲載。
jquery本体とプラグイン本体はサイトを直接指定している。
<html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js"></script> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> <script type="text/javascript"> window.onload=function(){ var json=[{"name":"Tom", "like":["apple", "peach"]}, {"name":"Mike", "like":["melon"]}]; $("#child").tmpl(json).appendTo( "#parent"); }; </script> </head> <body> <div id="parent"> <script id="child" type="text/x-jquery-tmpl"> Name:${name}<br/> Like: {{each like}} ${$value} {{/each}} <hr> </script> </div> </body> </html>
上のHTML & JavaScriptで以下の様な表示が行われる。
内容的にはサンプルのまんまなのだが、window.onloadで開いた際に定義されるjson変数を
$("#child").tmpl(json).appendTo( "#parent");
と呼び出すことで、以下の形式で指定することでHTMLのbody中に記載してある の間に記載されているテンプレート文法に変数がアサインされる。
JavaScriptでJSONを返却する様なAPIをAJAXで呼び出してそのコールバック受付時にHTML上の特定のDOMにテンプレートに従った形式で反映される様にするとか便利に使えそうだ。