mustache.js使用笔记

Mustache 是一款经典的前端模板引擎,在前后端分离的技术架构下面,前端模板引擎
是一种可以被考虑的技术选型,随着重型框架(AngularJS、ReactJS、Vue)的流行,
前端的模板技术已经成为了某种形式上的标配,Mustache 的价值在于其稳定和经典:
主页:https://github.com/janl/mustache.js/
文档:https://mustache.github.io/mustache.5.html

Mustache 在使用的时候,会在页面上出现 {{person}} 这样的标签,载入的时候回显
示出来,然后立即被替换掉,这个对于页面的呈现是不够友好的,这是我在使用的过

程中遇到的一个痛点。

<!DOCTYPE html> 
<html> 
<head> 
<title>mustache.js</title> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
</head> 
<body>
<div id="demo"></div>
<script type="text/x-mustache-template" id="template">
    <div>
    Hello {{name}}
    You have just won {{value}} dollars!
    {{#in_ca}}
    Well, {{taxed_value}} dollars, after taxes.
    {{/in_ca}}
    </div> 
    <div>{{company}}</div>
    <div>{{{company}}}</div>
    <div>
        {{#repo}}
          <b>{{name}}</b>
        {{/repo}}
    </div>
    <div>
        {{#wrapped}}
          {{name}} is awesome.
        {{/wrapped}}
    </div>
    <div>
        {{#person?}}
            Hi {{name}}!
        {{/person?}}
    </div>   
    <div>
        {{#repo_new}}
          <b>{{name}}</b>
        {{/repo_new}}
        {{^repo_new}}
          No repos :(
        {{/repo_new}}
    </div>  
    <div>
        <h1>Today{{! ignore me }}.</h1>
    </div>
</script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/mustache.js/2.3.0/mustache.js"></script>
<script type="text/javascript">
    var template = $('#template').html();
    //Mustache.parse(template);
    var temp = Mustache.render(template, {
        "name": "徐同保",
        "value": 10000,
        "taxed_value": 10000 - (10000 * 0.4),
        "in_ca": true,
        "company": "<b>GitHub</b>",
        "repo": [
            { "name": "resque" },
            { "name": "hub" },
            { "name": "rip" }
        ],
        "wrapped": function() {
            return function(text, render) {
                return '<b style="color:green;font-size:36px;">' + render(text) + '</b>';
            }
        },
        "person?": { "name": "Jon" },
        "repo_new": []
    });
    $('#demo').html(temp);
</script>
</body> 
</html> 

原文地址:https://www.cnblogs.com/xutongbao/p/9924942.html