Jemplate - Template-Toolkit like なJavaScriptのTemplateエンジン
Aloha! Casual perlerな皆さんこんにちは。CasualなPerlerの皆さんはJavaScriptのTemplateに何を使っていますか?世にいろいろJavaScriptのテンプレートエンジンはありますが、今日はPerlのTemplateモジュールであるTemplate-Toolkit likeな記法が書けるJemplateを紹介します。
インストール
% cpan Jemplate
簡単ですね。
Jemplate-runtimeのjs
Jemplateを使うためにはまずは、(x)html側でJemplate.jsを読み込む必要があります。
% jemplate --runtime > Jemplate.js
このようにして作成できますので(x)htmlで
<script src="Jemplate.js" type="text/javascript"></script>
のように読み込んであげましょう。
Hello Jemplate
では実際にJemplateエンジンを作ってみましょう。
hello.tt
Hello [% engine %]!
とりあえずこんな感じで簡単なテンプレートを作成してみます。
で、このテンプレートファイルをjemplateでコンパイルします。
% jemplate --compile hello.tt > hello.js
そうするとhello.jsの中身が下記のようなファイルになります。
/*
This JavaScript code was generated by Jemplate, the JavaScript
Template Toolkit. Any changes made to this file will be lost the next
time the templates are compiled.
Copyright 2006 - Ingy d旦t Net - All rights reserved.
*/
if (typeof(Jemplate) == 'undefined')
throw('Jemplate.js must be loaded before any Jemplate template files');
Jemplate.templateMap['hello.tt'] = function(context) {
if (! context) throw('Jemplate function called without context\n');
var stash = context.stash;
var output = '';
try {
output += 'Hello ';
//line 1 "hello.tt"
output += stash.get('engine');
output += '!\n';
}
catch(e) {
var error = context.set_error(e, output);
throw(error);
}
return output;
}
で、このhello.jsを先ほどのJemplate.jsを読み込んでいたところの後で読み込みましょう。
<script src="Jemplate.js" type="text/javascript"></script> <script src="hello.js" type="text/javascript"></script>
これで準備は完了です。実際にこのテンプレートを実行するscriptを書いてみましょう。
<html>
<head>
<title>test</title>
<script src="Jemplate.js" type="text/javascript"></script>
<script src="hello.js" type="text/javascript"></script>
</head>
<body>
<p id="greet">Hello HTML!</p>
<script>
Jemplate.process(
'hello.tt',
{engine: 'Jemplate'},
document.getElementById('greet')
);
</script>
</body>
</html>
今回はこのようなhtmlを用意しました。実効すると「Hello Jemplate!」と表示されます。
Jemplate.processの第二引数に渡すdataをXHR経由等で持ってきたりすると夢がひろがりんぐですね。
その他の詳しい使い方等はpodをご覧ください。