Reputation: 1
I am using underscore in my external templates(using require.js) and trying to access the data inside document.ready function. But I get the above mentioned error while executing the template.
Below is the code snippet
<script>
$(document).ready(function(){
<%_.each(people, function(person){ %>
console.log(<%=person%>);
<% }); %>
});
</script>
Where am I going wrong? All help will be much appreciated. Thanks
Upvotes: 0
Views: 457
Reputation: 434665
You seem to be a bit confused about how templates work. You need two separate things:
<script type="text/x-underscore">
container. We use <script>
with a non-HTML and non-JavaScript type
to keep the browser from trying to interpret the template data in any way, we want the browser to leave the template alone so that we can have our way with it via _.template
._.template
to create a function representation of the template and then call that function to get your HTML.So, if you wanted to produce a list of people, you'd have a template like this:
<script id="t" type="text/x-underscore">
<% _(people).each(function(person) { %>
<%= person %>
<% }); %>
</script>
and then you'd have some JavaScript like this to use it:
<script type="text/javascript">
$(document).ready(function() {
var people = [ 'Tom', 'Dick', 'Harry' ];
var tmpl = _.template($('#t').html());
$('body').append(tmpl({
people: people
}));
});
</script>
Note that there is no <% ... %>
stuff in the <script type="text/javascript">
, that stuff goes in the template.
You can call whatever JavaScript you want inside the template so you could also do this:
<script id="t" type="text/x-underscore">
<% _(people).each(function(person) { %>
<% console.log(person) %>
<% }); %>
</script>
Of course, if that's all you wanted to do then you wouldn't use a template at all, you'd just write some JavaScript:
<script type="text/javascript">
$(document).ready(function() {
var people = [ 'Tom', 'Dick', 'Harry' ];
_(people).each(function(person) { // Or any of the other ways of looping over people...
console.log(person);
});
});
</script>
Here's a quick demo of the above: http://jsfiddle.net/ambiguous/V7DXv/
Upvotes: 2