I have just started using jQuery templates.
I have a question that the documentation hasn’t been able to answer for me (yet).
My template is…
<script id="restaurant-review-template" type="text/x-jQuery-tmpl">
<li>
<span class="rating rating-${rating}">
${$item.getRating()}
</span>
</li>
</script>
…and my invocation code is…
$('#restaurant-review-template').tmpl(allRestaurants, {
getRating: function() {
// Is it possible to access the array element here?
// Ideally, if `this` was the current array member...
return new Array((this.rating || 0) + 1).join('*');
}
}).appendTo('#cont')
In my allRestaurants array, I have objects which have a rating property which contains an number.
I want to return a list of asterixes for the number in the rating property. For example, if the rating property held 4, I’d like to output ****.
I know I could do something like…
allRestaurants = allRestaurants.filter(function(element) {
element.asterixes = new Array((element.rating || 0) + 1).join('*');
return true;
});
…but I’d rather not polute the array with that extra property just for the template.
So, within a custom template function such as above, is there a way to access the current array element (I did console.log(this, arguments) and couldn’t see anything useful).
If not, what is the cleanest way to achieve this?
Basically all item’s data is located in
this.data, so you can reach rating value withthis.data.rating.