假装异步加载中...
11 Mar 2015

Mustache.js 基础

mustache.js 是 mustache 模板系统的 javascript 实现。

你可以在任何可以使用 javascript 的地方使用 mustache.js。例如:浏览器,服务器端(node,CouchDB views)。

mustache.js 支持 CommonJS module API,也支持 Asynchronous Module Definition API

使用

使用 mustache.js 简单例子:

var view = {
  title: "Joe",
  calc: function () {
    return 2 + 4;
  }
};

var output = Mustache.render(" spends ", view);

Mustache.render 函数接受两个参数:

1)mustache 模板

2)一个 view 对象,它包含需要渲染到模板中的数据和代码

模板

mustache 模板是包含若干 mustache tag 的字符串。

有很多种加载模板的方式,其中两种是:

Include Templates

直接写在 HTML 文件中,下例中用到了 jQuery:

<html>
<body onload="loadUser">
<div id="target">Loading...</div>
<script id="template" type="x-tmpl-mustache">
Hello !
</script>
</body>
</html>
function loadUser() {
  var template = $('#template').html();
  Mustache.parse(template);   // optional, speeds up future uses
  var rendered = Mustache.render(template, {name: "Luke"});
  $('#target').html(rendered);
}

Load External Templates

如果你的模板存在于独立文件中,你可以异步加载它们,加载完成后再渲染,同样用到了 jQuery:

function loadUser() {
  $.get('template.mst', function(template) {
    var rendered = Mustache.render(template, {name: "Luke"});
    $('#target').html(rendered);
  });
}

mustache tag 有下面几种,详细内容参见 Mustache 基础。后面我们只谈 mustache.js 特殊的地方。

Variables

可以使用 JavaScript’s dot notation 获取 view 中对象的属性

View:

{
  "name": {
    "first": "Michael",
    "last": "Jackson"
  },
  "age": "RIP"
}

Template:

*  
* 

Output:

* Michael Jackson
* RIP

Sections

False Values or Empty Lists

如果 person 键不存在,或者存在但值为 null, undefined, false, 0, or NaN,或者是一个空字符串或者空列表,则不会渲染。

View:

{
  "person": false
}

Template:

Shown.

Never shown!

Output:

Shown.

Non-Empty Lists

如果 person 键存在,且值为非空列表,则渲染一次或多次。

View:

{
  "stooges": [
    { "name": "Moe" },
    { "name": "Larry" },
    { "name": "Curly" }
  ]
}

Template:


<b></b>

Output:

<b>Moe</b>
<b>Larry</b>
<b>Curly</b>

在循环字符串数组时,. 可以用来引用当前的 item

View:

{
  "musketeers": ["Athos", "Aramis", "Porthos", "D'Artagnan"]
}

Template:


* 

Output:

* Athos
* Aramis
* Porthos
* D'Artagnan

如果一个 section variable 是一个函数,它会在当前 item 的 context 中调用。(注意和下面的函数块相区别,类似于 eachwith)

View:

{
  "beatles": [
    { "firstName": "John", "lastName": "Lennon" },
    { "firstName": "Paul", "lastName": "McCartney" },
    { "firstName": "George", "lastName": "Harrison" },
    { "firstName": "Ringo", "lastName": "Starr" }
  ],
  "name": function () {
    return this.firstName + " " + this.lastName;
  }
}

Template:


* 

Output:

* John Lennon
* Paul McCartney
* George Harrison
* Ringo Starr

Functions

It is called in the context of the current view object.

View:

{
  "name": "Tater",
  "bold": function () {
    return function (text, render) {
      return "<b>" + render(text) + "</b>";
    }
  }
}

Template:

Hi .

Output:

<b>Hi Tater.</b>

Inverted Sections

只有当值为 null, undefined, false, falsy 或是一个空列表时才会渲染。

View:

{
  "repos": []
}

Template:

<b></b>
No repos :(

Output:

No repos :(

Comments

<h1>Today.</h1>

Will render as follows:

<h1>Today.</h1>

Partials

在 mustache.js 中,一个 partials 对象可以作为第三个参数传给 Mustache.render。partial 对象的 key 必须为 partial 的 name,value 是 partial text。

Mustache.render(template, view, {
  user: userTemplate
});

Set Delimiter

* 

* <% erb_style_tags %>
<%==%>
* 

Pre-parsing and Caching Templates

默认情况下,mustache.js 第一次解析一个模板之后,它会缓存整个 parsed token tree。下次它遇到相同的 template 时,就会跳过解析的步骤,更快的渲染模板。如果你愿意,你可以提前使用 mustache.parse 来做解析。

Mustache.parse(template);

// Then, sometime later.
Mustache.render(template, view);

Plugins for JavaScript Libraries

mustache.js may be built specifically for several different client libraries, including the following:

These may be built using Rake and one of the following commands:

$ rake jquery
$ rake mootools
$ rake dojo
$ rake yui3
$ rake qooxdoo

Command line tool

mustache.js 自带一个基于 node 的命令行工具,它可以作为全局工具安装。

$ npm install -g mustache
$ mustache dataView.json myTemplate.mustache > output.html

# also supports stdin
$ cat dataView.json | mustache - myTemplate.mustache > output.html

or as a package.json devDependency in a build process maybe?

$ npm install mustache --save-dev
{
  "scripts": {
    "build": "mustache dataView.json myTemplate.mustache > public/output.html"
  }
}
$ npm run build

命令行工具基本上是 Mustache.render 的一个包装,所以上面提到的功能都具备。

发现文章有错误或是有疑问,欢迎骚扰:395217502@qq.com
上一篇: Mustache 基础
上一篇: Handlebars.js 基础
comments powered by Disqus