jQueryでテンプレートエンジン
jQueryのプラグインにjTemplatesなるテンプレートエンジンがあったので使ってみる。
ということで
Json.NETをさわってみるで書いたJSONデータをjQueryで加工して、HTMLに整形するコードをjTemplatesを使って書き直してみる。取り扱うJSONデータは以下↓
[{"ID":1,"Name":"ジョン"},{"ID":2,"Name":"ボブ"},{"ID":3,"Name":"ジャック"},{"ID":4,"Name":"ディラン・マッケイ"}]
以前は、
$.each(data, function(i, customer) { $("#dataTable").append( $("<tr>").append( $("<td>").text(customer.ID), $("<td>").text(customer.Name) ) ); });
のようにjQueryAPIを使って、ごりごりとHTMLを生成していた。まずはこの処理をテンプレートファイルに分離する。
「index.tpl」というファイル名でテンプレートファイルを作る(拡張子は別に決まっていない)
index.tpl
{#template MAIN} <table id="dataTable" border="1"> <tr> <th>ID</th> <th>名前</th> </tr> {#foreach $T as customer} <tr> <td>{$T.customer.ID}</td> <td>{$T.customer.Name}</td> </tr> {#/for} </table> {#/template MAIN}
- 「{#template テンプレート名}」でテンプレートの定義を開始する。「{/#template テンプレート名}」で定義の終了。
- 1つのテンプレートファイルの中にテンプレートの定義は複数できて、それぞれ呼び出す事ができる。
- 「{#foreach コレクション要素 as 変数名}」でコレクション要素の数だけ「{#/for}」までの処理を繰り返す。
- 「$T」は外部から渡されたデータを表す(他にも何種類かある)
あとは「index.htm」のHTML整形部分をテンプレートファイルを読み込む処理に書き換える。
index.htm
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Json.NET テスト</title> <script type="text/javascript" src="js/jquery-1.2.1.js"></script> <script type="text/javascript" src="js/jquery-jtemplates.js"></script> <script type="text/javascript"> $(document).ready(function() { $.getJSON("./json.aspx", function(data) { $("#result").setTemplateURL("./index.tpl"); $("#result").processTemplate(data); }); }); </script> </head> <body> <div id="result"></div> </body> </html>
- 「setTemplateURL」の引数にテンプレートファイルのURLを指定する。
- 「processTemplate」でデータを渡して、テンプレートを処理する。
これで同じ結果を得られる。
いわゆるビューの部分をテンプレートファイルに分離した事で結果の画面がわかりやすくなったと思う。
コードもだいぶすっきりした。