您当前的位置: 首页 > 

彭世瑜

暂无认证

  • 0浏览

    0关注

    2791博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

彭世瑜 发布时间:2020-05-06 10:52:11 ,浏览量:0

多种语言实现: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



Loading...


  hello {{name}}



  (function () {
    var template = document.getElementById("template").innerHTML;
    var rendered = Mustache.render(template, { name: "Tom" });
    document.getElementById("target").innerHTML = rendered;
  })();

异步加载模板

模板文件 template.html

hello {{name}}

异步渲染



Loading...


  (function () {
    fetch("./template.html")
      .then((response) => response.text())
      .then((template) => {
        var rendered = Mustache.render(template, { name: "Tom" });
        document.getElementById("target").innerHTML = rendered;
      });
  })();

关注
打赏
1665367115
查看更多评论
立即登录/注册

微信扫码登录

0.2501s