【发布时间】:2018-02-22 20:00:36
【问题描述】:
我想测试 John Resig 微模板引擎https://johnresig.com/blog/javascript-micro-templating/,但它不渲染 123 而是显示文字模板
更新代码出现错误
未捕获的类型错误:无法读取 null 的属性“innerHTML” 在 tmpl (index2.html:19) 在 index2.html:58
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Test</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
// Simple JavaScript Templating
// John Resig - https://johnresig.com/ - MIT Licensed
(function(){
var cache = {};
this.tmpl = function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');");
// Provide some basic currying to the user
return data ? fn( data ) : fn;
};
})();
</script>
</head>
<body>
<script>
var data = [
{
"id":"123",
},
{
"id":"456",
}
]
var id1 = data[0].id
document.body.innerHTML = tmpl("item_tmpl", id1);
</script>
<script type="text/html" id="item_tmpl">
<div>
<%=id1%>
</div>
</script>
</body>
</html>
【问题讨论】:
-
您是否尝试查看控制台日志?应该是脚本错误
-
@Pierre 在 chrome 控制台中没有错误。
标签: javascript templating