Right now I’m using the following line of code to retrieve an Underscore template and create a DOM element from the template, using jQuery.
var element = $(_.template($('#template').html())());
It works, but I think this looks a bit messy/confusing, so I was wondering if there’s a better way to do this?
Updated for Underscore 1.7+: There’s really not much better you can do in newer versions of Underscore since
_.templatealways returns a function:You used to be able to say
_.template(tmpl, data)(see below) to get a filled-in template but no longer.You can however hide some of the parentheses inside a function with things like:
or:
For old versions of Underscore: You can get the filled in template from
_.templateby supplying thedataparameter:Anything truthy will probably due for
databut an empty object is probably your best bet:That’s still a bit noisy but you can always wrap the
_.templatecall in another function:How you bust it into functions depends on your preference what parts you’d be using elsewhere.