mustache.js一个零依赖的模板系统实现

多种语言实现:http://mustache.github.io/

js版本文档:https://github.com/janl/mustache.js


简介:

mustache.js is a zero-dependency implementation of the mustache template system in JavaScript.

Node 环境使用

安装

$ npm install mustache --save

基本语法

变量: {{name}}
列表:{{#list}}{{.}}{{/list}}
对象:{{obj.name}} - {{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://unpkg.com/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://unpkg.com/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>


上一篇:利用“域名后缀”的漏洞劫持国家*域名(一)


下一篇:Windows 上 GitHub Desktop 的操作