I'm with a problem when using underscorejs. It's not beeing possible render the template correctly. Looks like the variable passed need to be global, but is it really true? I would like to avoid this. I'm getting this error: Uncaught ReferenceError: items is not defined. If I use items instead of var items, the things work. But I would like to avoid this. How can I fix it?
This code was adapted from this 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}));
}