Mustache 入门教程

Mustache 简介:

Mustache 是一个轻逻辑模板解析引擎,它的优势在于可以应用在 Javascript、PHP、Python、Perl 等多种编程语言中。

Mustache 语法:

Mustache 的模板语法很简单,就那么几个:

  • {{keyName}}
  • {{#keyName}} {{/keyName}}
  • {{^keyName}} {{/keyName}}
  • {{.}}
  • {{<partials}}
  • {{{keyName}}}
  • {{!comments}}

传统

传统的写后台ajax过来的数据我们会 :

$.each(messages.reverse(), function(index, message) {
    $('#messageList').append(
        '<li><span class="list-title">' +
        message.userName + '</span>' +
        '<abbr class="list-timestamp" title="' +
        message.datePosted + '"></abbr>' +
        '<p class="list-text">' + message.messageText + '</p></li>');
    }
});

不停的进行字符串的拼接,那么使用mustache后,我们可以 :

<div id="wrap2">
    <script id="myTemplate" type="x-tmpl-mustache">
    {{#stooges}}
      <li> hello {{name}} </li>
    {{/stooges}}
    </script>
</div>

<script>
    var data = {
        "company": "Apple",
        "address": {
            "street": "1 Infinite Loop Cupertino</br>",
            "city": "California ",
            "state": "CA ",
            "zip": "95014 "
        },
        "product": ["Macbook ","iPhone ","iPod ","iPad "],
        "stooges": [
        { "name": "Moe" },
        { "name": "Larry" },
        { "name": "Curly" }]
    }
    var tpl = $("#myTemplate").html();
    var html = Mustache.to_html(tpl,data);
    $("#wrap2").append(html)
</script>

mustache 使用

{{keyName}}

{{}}就是 Mustache 的标示符,花括号里的 keyName 表示键名,这句的作用是直接输出与键名匹配的键值,例如:

var tpl = '{{company}}';
var html = Mustache.render(tpl, data);
//输出:
Apple

{{#keyName}}{{/keyName}}

var tpl = '{{#stooges}} <li>hello {{name}}</li> {{/stooges}}';
var html = Mustache.render(tpl, data);
//输出:
<li> hello Moe </li>
<li> hello Larry </li>
<li> hello Curly </li>
注意:如果{{#keyName}} {{/keyName}}中的 keyName 值为 null, undefined, false;则不渲染输出任何内容。

{{^keyName}} {{/keyName}}

该语法与{{#keyName}} {{/keyName}}类似,不同在于它是当 keyName 值为 null, undefined, false 时才渲染输出该区块内容。

var tpl = {{^nothing}}没找到 nothing 键名就会渲染这段{{/nothing}};
var html = Mustache.render(tpl, data);
//输出:
没找到 nothing 键名就会渲染这段

{{{keyName}}}

{{keyName}}输出会将等特殊字符转译,如果想保持内容原样输出可以使用{{{}}},例如:

var tpl = '{{#address}} <p>{{{street}}}</p> {{/address}}'
//输出:
<p>1 Infinite Loop Cupertino</br></p>

{{!comments}}

!表示注释,注释后不会渲染输出任何内容。

{{!这里是注释}}
//输出:
posted @ 2019-09-08 19:33  吴川华仔博客  阅读(3511)  评论(0编辑  收藏  举报