mustache.js 模板应用示例

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
<title>mustache.js 示例</title>
<script type="text/javascript" src="mustache.js"></script>

</head>
<body>

<div>
<script language="javascript">
var data, template, html;
data = {
    name : "Some Tuts+ Sites",
    sites: ["Nettuts+", " Psdtuts+", "Mobiletuts+"],
    url : function () {
        return function (text, render) {
            text = render(text);
            var url = text.trim().toLowerCase().split('tuts+')[0]+ '.tutsplus.com';
            return '<a href="' + url + '">' + text + '</a>';
        }
    }
};

template = " \
<h1> {{name}} </h1>  \
<ul> {{#sites}} \
    <li> {{#url}} {{.}} {{/url}} </li> \
    {{/sites}}\
</ul>"; 
  
html = Mustache.render(template, data);
  
document.write(html);

</script>

</div>
</body>
</html>

When looping over an array of strings, a .
can be used to refer to the current item in the list.
在本示例中,{{.}} 引用的就是 sites 数组的一个值;

为何不可以直接引用 GitHub 上的 mustache.js 文件?
  • Chrome 给出的错误:

Refused to execute script from 'https://raw.githubusercontent.com/janl/mustache.js/master/mustache.js' because its MIME type ('text/plain') is not executable, and strict MIME type checking is enabled.
其 Response Header 为:Content-Type:text/plain; charset=utf-8,因为通常为 Content-Type:application/javascript; charset=utf-8

后记
  • 今天是 12 月 23 日,距离本文写作已有 9 个多月,看到 NoteCode 的 被我误解的模板引擎-mustache,就想起了早先的这篇文章;
  • 本例中有一个示例 url 处理函数;请结合 Mustache 用法Chrome 调试 进行理解;
  • 看来 js 中的 function 需要继续深刻理解,如果理解透彻,就会帮助改进 js 代码的写法了,而不至于开发人员自己写 for 循环了;
  • 看来 code review 是要实施起来;
  • 可能要深刻理解 js,必须读读这些库的代码,深入了解其实现机理;
  • 模板、数据和逻辑
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容