jquery-tmplとやや互換性のある、高速で柔軟なテンプレートエンジン jquery-ptmpl を作りました
jquery-tmplに対する不満を解消するため、テンプレートエンジンを自作しました。
ついでに、jquery-tmplより2倍から10倍以上高速に動作するようです。 (リポジトリのベンチマーク参照)
ソースコードはgithubで公開しています。
200行程度しかないので読みやすいはず。
jQuery Pluggable Templates Plugin
https://github.com/atsumu/jquery-ptmpl
サンプルコード
<div id="place"></div> <script id="tmpl-sample" type="text/x-jquery-tmpl"> <h2>this is sample.</h2> {{! you can use template local variable. }} {{$ var foo = '<span style="color:red">output raw html</span>'; }} {{html foo}} {{each(k, v) a}} {{if v % 2 == 0}} {{continue}} {{else v % 3 == 0}} {{break}} {{else}} <div>k={{= k}}, v={{= v}}</div> {{/if}} {{/each}} {{tmpl({ b:3 }) "#tmpl-other"}} </script> <script id="tmpl-other" type="text/x-jquery-tmpl"> here is other template. {{= b}} </script> <scirpt> jQuery(function ($) { $("#tmpl-sample").ptmpl({ a:[1,2,3,4] }).appendTo("#place"); }); </script>
jquery-ptmplの特徴
ローカル変数が使える
<script id="tmpl-sample" type="text/x-jquery-tmpl"> {{$ var foo = "bar"; }} {{= foo}} </script>
{{$ ...}}の中に書いたコードは、コンパイル後のコードの中にそのまま埋め込まれます。
1テンプレート=1関数としてコンパイルされるので、定義した変数は同じテンプレート内でのみ有効です。
タグを定義できる
<script> jQuery.ptmplDefineTag({ '=': function (code, str) { code.push('_PTMPL_HTML.push(jQuery.ptmplEscapeHtml((', str, ')));'); }}); </script>
のように、jQuery.ptmplDefineTag関数を使ってテンプレートタグを定義できます。