Do You PHP はてブロ

Do You PHPはてなからはてブロに移動しました

JsRenderチュートリアル - 他のテンプレートを読み込む際にコンテンツを渡す

JavaScript製でjQuery非依存なテンプレートエンジンであるJsRender/JsViewsを使ったチュートリアルを書いてみようと思います。
以前に書いたエントリJsRender入門 - Do You PHP はてなも参照してください。

今回やること

他のテンプレートを読み込む際にコンテンツを渡す

コード

<html>
<body>

<!-- レンダリング結果を表示するスペース -->
<div id="result"></div>

<script src="https://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script src="http://www.jsviews.com/download/jsviews.min.js" type="text/javascript"></script>
<script type="text/javascript">
// テンプレートのinclude - コンテンツとして値を渡す
$(function() {
    // 表示するデータ(オブジェクト)
    var fruits = { name: "りんご", num: 3 };

    // テンプレートに変数fruitsを渡し、レンダリング結果を表示
    $('#result').html(
        $('#template').render(fruits)
    );
});
</script>

<!-- テンプレート -->
<script id="template" type="text/x-jsrender">
    <p>{{:name}}{{:num}}個あります</p>
    {{include tmpl="#template_child"}}
        <i>{{>name}}</i>が<i>{{>num}}</i>個ありますよん
    {{/include}}
</script>
<script id="template_child" type="text/x-jsrender">
    <p>template_child内</p>
    {{include tmpl=#content/}}
</script>
</body>
</html>

説明

他のテンプレートには変数の他にコンテンツをそのまま渡すこともできます。この場合、includeタグの値としてコンテンツを指定します。

    {{include tmpl="#template_child"}}
        <i>{{>name}}</i>が<i>{{>num}}</i>個ありますよん
    {{/include}}

子テンプレートでは、テンプレート名に"#content"を指定してコンテンツをincludeします。

    {{include tmpl=#content/}}

JSFiddleで動作を見る