I am trying to use underscore.template to compiles a JavaScript templates by loading an html through jQuery.get
in this way:
_.template($.get('my_template.html'), $get(function(data) {
return data;
}));
but I get the following message
TypeError: Object #<Object> has no method 'replace'
Any hints?
$.get
doesn't work the way you think it does. $.get('my_template.html')
doesn't return my_template.html
, it returns a jqXHR
, the thing you're GETting is passed to the $.get
callback:
$.get('my_template.html', function(html) {
// my_template.html will be in `html` here.
});
So if you really want to use $.get
to retrieve your template, you're going to have to wait for the AJAX call to return something from the server and that won't happen until later. You could make a synchronous AJAX request using the async
option to $.ajax
:
async (default:
true
)
Type: Boolean
By default, all requests are sent asynchronously (i.e. this is set totrue
by default). If you need synchronous requests, set this option to false. [...] Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
That would look like this:
var tmpl;
$.ajax({
url: 'my_template.html',
type: 'get',
async: false,
success: function(html) {
tmpl = html;
}
});
var t = _.template(tmpl);
// `t` is now your compiled template function
I don't recommend this though, async:false
is a nasty thing to do to your users and using it will make people think your application has locked up or crashed.
I would find a different way to load your templates. Throw them all in <script>
elements so they're always available or deliver them along with whatever JavaScript is going to use them.