naoyaさん のJemplateの記事に触発されて埋め込みjavascriptを実装してみました。
同様の実装として Ajax Pages があるのですが、よりシンプルに実装してみました。コードにして50行。
これは今作っているフレームワークの一部です。シンプルですがわりと使えるかと。 実際の動作はサンプルファイルを見ていただくとして
lyase_view.jsの説明どおり
/*
* using innerHTML
* -------------
* //in HTML
* <textarea id="template" style="display:none">
* The value of x is:< %= context.x%>
* </textarea>
* //code
* document.write(Lyase.View.render({element:"template"}, {x : 10}));
*
* using a template file
* -------------
* //in /template.jhtml
* The value of x is:< %= context.x%>
* //code
* document.write(Lyase.View.render({file:"/template.jhtml"}, {x : 10}));
*
* Of course, you can embed more complex codes.
* //in HTML, with prototype.js
* <textarea id="template" style="display:none">
* < % context.list.each(function(pair){%>
* The value of < %= pair.name %> is: < %= pair.value%>
* < % }) %>
* </textarea>
* //code
* document.write(Lyase.View.render({element:"template"},
* {list :[{name : "x", value : 10}, {name : "y", value : 20}]}));
*/
こんな感じでjavascriptのコードが読み込めます。
また
<h1>< %= context.title %></h1>
この文章はLyase.Viewを使用して< %= context.fileName %>の内容を表示しています。
以下のようにクロージャも問題なく使用できます。
< % var c = "," %>
< % context.list.each(function(num){ %>
< %= num+c %>
< % })%>
< %= render({file :"./sample2.jhtml"}, context)%> <!--ココに注目--!>
このようにテンプレート内で別のテンプレートを呼び出すことも可能です。
テンプレートには文字列、textareaなどのinnerHTML、テンプレートファイルが使用できます。 prototype.jsのAjax.Updaterあたりをハックすれば結構使えるものになるんじゃないかなあ、と思ってみたり。