Handlebars模板引擎demo

介紹html

Handlebars 是 JavaScript 一個語義模板庫,經過對view和data的分離來快速構建Web模板。它採用」Logic-less template」(無邏輯模版)的思路,在加載時被預編譯,而不是到了客戶端執行到代碼時再去編譯, 這樣能夠保證模板加載和運行的速度。Handlebars兼容Mustache,你能夠在Handlebars中導入Mustache模板。jquery

如下是我學習Handlebars的第一個demo。頁面引入handlebars.js和jquery.js。json

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>黃寶康的第一個Handlebars案例</title>
    <script src="handlebars.js"></script>
    <script src="jquery.js"></script>

</head>
<body>
<script id="tpl" type="text/x-handlebars-template">
    <div class="demo">
        <h1>{{name}}</h1>
        <p>{{content}}</p>
    </div>
</script>
<script>
    var source = $("#tpl").html();// 獲得模板原始內容
    var template = Handlebars.compile(source);//編譯以後返回類型爲Function
    var json = {name:'黃寶康',content:'個人第一個Handlebars模板引擎demo'};//模擬數據
    var html = template(json);// 函數調用以後返回填充後的數據
    $('body').html(html);
</script>
</body>
</html>

頁面效果:
這裏寫圖片描述less

相關文章
相關標籤/搜索