Search code examples
jqueryjquery-templates

Can I access the current element in a jQuery templates custom function?


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')

jsFiddle.

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;
});

jsFiddle.

...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?


Solution

  • Basically all item's data is located in this.data, so you can reach rating value with this.data.rating.

    element.asterixes = new Array((this.data.rating || 0) + 1).join('*');