【发布时间】:2015-03-27 13:10:36
【问题描述】:
我在使用underscorejs 时遇到问题。无法正确渲染模板。看起来传递的变量需要是全局的,但这是真的吗?我想避免这种情况。我收到此错误:Uncaught ReferenceError: items is not defined。如果我使用 items 而不是 var items,则一切正常。但我想避免这种情况。我该如何解决?
这段代码改编自question。
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<script data-main="index" src="require.min.js"></script>
</head>
<body>
<script id='template' type="text/x-underscore">
<table cellspacing='0' cellpadding='0' border='1' >
<thead>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<%
// repeat items
_.each(items,function(item,key,list){
// create variables
var f = item.name.split("").shift().toLowerCase();
%>
<tr>
<!-- use variables -->
<td><%= key %></td>
<td class="<%= f %>">
<!-- use %- to inject un-sanitized user input (see 'Demo of XSS hack') -->
<h3><%- item.name %></h3>
<p><%- item.interests %></p>
</td>
</tr>
<%
});
%>
</tbody>
</table>
</script>
<div id="target"></div>
</body>
</html>
index.js:
var application = {
initialize: function() {
this.load();
},
jsPool: [
'jquery-1.11.2.min.js',
'underscore-min.js',
],
load: function() {
define(
this.jsPool,
this.onReady
);
},
onReady: function() {
render();
}
};
application.initialize();
function render() {
var items = [
{name:"Alexander"},
{name:"Barklay"},
{name:"Chester"},
{name:"Domingo"},
{name:"Edward"},
{name:"..."},
{name:"Yolando"},
{name:"Zachary"}
];
var template = $("#template").html();
$("#target").html(_.template(template,{items:items}));
}
【问题讨论】:
标签: javascript html underscore.js template-engine