This template is completely valid; the compiled JavaScript version is shown below:
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;
}
Everything looks good so far. By the way, you can view the JavaScript code for the template by accessing the source
property of a compiled Underscore template:
var t = _.template(raw_template);
console.log(t.source);
However, there's a catch. The issue arises because the FB.api
call is asynchronous. Here's what actually happens:
- The template is compiled and executed.
FB.api
is called asynchronously.
- The template returns HTML which is added to the DOM.
- Some time passes.
- Finally, the callback from Facebook is triggered.
- At this point, it's too late to update the template content since it has already been inserted into the DOM.
To resolve this, you need to restructure your logic. Move the FB.api
call outside of the template like this:
var t = _.template(...);
FB.api('/mu', function(response) {
var html = t({ response: response });
// Add the html to the DOM here
});
This change ensures that the template is only used once all the necessary data is available.