Handlebars模板引擎簡單使用

  本例展現用Handlebars對一小段簡單HTML模板進行渲染填充而後顯示在頁面。javascript

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=utf-8">
    <title>Handlebars模板填充樣例</title>
    <script type="text/javascript" src="../jquery-2.1.1.min.js"></script>
    <script type="text/javascript" src="../handlebars-v3.0.1.js"></script>
</head>
<body>    
    <div id="content"></div>

    <!-- 模板 -->
    <script id="entry-template" type="text/x-handlebars-template">
        <div class="entry">
            <h1>{{title}}</h1>
            <div class="body">{{body}}</div>
        </div>
    </script>

    <script type="text/javascript">
        // 編譯模板
        var source   = $("#entry-template").html();
        var template = Handlebars.compile(source);

        // 數據
        var data = {
            title: "My New Post",
            body: "This is my first post!"
        }

        // 用編譯後的模板對象,填充渲染JSON數據
        $(function () {
            var html = template(data);
            $("#content").html(html);
            // alert(Handlebars.escapeExpression(html)); //對<>進行轉義,其在DOM再也不具備標籤含義。
        })
    </script>

</body>
</html>
相關文章
相關標籤/搜索