简介:
mustache.js is a zero-dependency implementation of the mustache template system in JavaScript.
Node 环境使用
安装
$ npm install mustache --save
基本语法
变量: {{name}}
列表:{{#list}}{{.}}{{/list}}
对象:{{}} - {{obj.age}}
代码示例
const Mustache = require("Mustache");
var data = {
name: "Tom",
age: 23,
};
var template = "my name is {{name}}, and {{age}} years old";
var result = Mustache.render(template, data);
console.log(result);
// my name is Tom, and 23 years old
浏览器中使用
最终效果是把id=template
的内容渲染后替换到id=target
<script src="https:///mustache@latest"></script>
<div id="target">Loading...</div>
<script id="template" type="x-tmpl-mustache">
hello {{name}}
</script>
<script>
(function () {
var template = document.getElementById("template").innerHTML;
var rendered = Mustache.render(template, { name: "Tom" });
document.getElementById("target").innerHTML = rendered;
})();
</script>
异步加载模板
模板文件 template.html
hello {{name}}
异步渲染
<script src="https:///mustache@latest"></script>
<div id="target">Loading...</div>
<script>
(function () {
fetch("./template.html")
.then((response) => response.text())
.then((template) => {
var rendered = Mustache.render(template, { name: "Tom" });
document.getElementById("target").innerHTML = rendered;
});
})();
</script>