The underscore template documentation suggest the following should be possible, yet it is not working for me. Executing the template simply returns nothing for this.
<% FB.api('/me', function(response){ %>
<%= response.name %>
<% }); %>
That's a perfectly valid template; in fact, the compiled JavaScript version looks like this (reformatted for readability):
function(obj) {
var __p = '';
var print = function() { __p += Array.prototype.join.call(arguments, '') };
with(obj || {}) {
__p += '\n';
FB.api('/me', function(response) {
__p += '\n' + response.name + '\n';
});
__p += '\n';
}
return __p;
}
And there's nothing wrong with that. BTW, you can look at the source attribute of a compiled Underscore template if you want to see the JavaScript for the template:
var t = _.template(raw_template);
console.log(t.source);
However, it won't do what you're expecting it to do. Your problem is that the FB.api call is an AJAX call and A stands for asynchronous. So by the time your callback gets called (i.e. <%= response.name %> is executed), the template will have been converted to HTML and added to the DOM and nothing will be looking at the __p variable anymore. The sequence looks something like this:
FB.api gets called.FB.api callback gets called.response.name is appended to the __p buffer.You're going to have to turn your logic inside out a bit. Your FB.api call should be outside your template:
var t = _.template(...);
FB.api('/mu', function(response) {
var html = t({ response: response });
// Somehow add html to the DOM
});
so that you don't try to use the template until all the data is ready.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With