Reputation: 2535
I want to localize templates in my Phonegap/Backbone mobile App. I want to somehow override underscore render function in a way that would always append extra attribute with languages. Let me show that on example:
lets say I required (require.js) the HomeView template wich looks like:
<div>
<p><%= language.get('someText') %></p>
</div>
In my HomeView.js I have:
var template = _.template(HomeTemplate);
this.$el.html( template({language: LanguageModel}));
This works, but I don't want to always append this language attribute to underscore template. Could I somehow overwrite that render function so It would always include language Model?
Upvotes: 1
Views: 97
Reputation: 434685
You can put any JavaScript expression you like inside <%= ... %>
. In particular, you can access globals. So, if you have a global application namespace:
// I'll call it `app` for lack of a better placeholder.
window.app = { ... };
Then you can put language
in there:
app.language = your_language_model;
and access it in any template without supplying anything extra to the _.template
call or the compiled template function:
var t = _.template('<%= app.language.get('pancakes') %>');
var h = t();
Demo: http://jsfiddle.net/ambiguous/jkmG7/1/
Upvotes: 1