You seem to be a bit confused about how templates work. You need two separate things:
- The template. This often goes inside a
<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.
- The JavaScript that uses the template. This is where you call
_.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/
<script type="text/x-underscore">element.<% ... %>stuff isn't JavaScript so you can't put them inside a$(document).ready()callback function._(people).each(function(p) { console.log(p) })in the callback though._(<%= people %>.each(function(person) {...}. But this doesn't work.How do I get the value that is sent by the view to the template?