I am trying to add the helper function to my underscore
template. But I am not able to do this. any one can please correct me?
here is my tempalate:
<script type="text/template" id="table">
<table>
<tbody>
<tr>
<% _.each(obj.titles, function(item){ %>
<td><%= item.label %>
<% }); %>
</tr>
</tbody>
</table>
</script>
Here is my js:
var viewHelper = {
getProperty: function(propertyName) {
console.log('getProperty ' + propertyName);
return propertyName;
}
};
var obj = {
"titles" : [
{"label" : "-----Totals for Month---- "},
{"label":"-----Previous Year-----"}
]
};
var template = _.template($('#table').html());
var html = _.extend(obj, viewHelper);
$('body').html(template(html));
But I am not able to get any call in to my helper function at all..
please update in to my fiddle;
It works fine with your code. You just have to use the function in your template:
<script type="text/template" id="table">
<table>
<tbody>
<tr>
<% _.each(obj.titles, function(item){ %>
<td><%= item.label %></td>
<% }); %>
</tr>
<tr>
<% _.each(obj.titles, function(item){ %>
<td><%= getProperty(item.label) %></td>
<% }); %>
</tr>
</tbody>
</table>
</script>
This is a working plunkr: http://plnkr.co/edit/akeiPbQoZBjzgBsEykTi?p=preview