I'm using an underscore template to create an HTML list, this list contains a date field that I would like to globalize. A simplification of the template looks like this:
<li>Date: <%= date %> </li>
This date is a Javascript date object, so don't want to print the value directly, I would like to print it using globalize. Without the template the solution should look like this:
var html = "<li>Date: " + Globalize.format(settings.get('lastUpdate'),'F') + "</li>";
Do you think I can use the template to achieve this or I must use a workaround?
You can call any globally accessible function inside your template. So, if
Globalize
is global (i.e. a property ofwindow
), then this template:will work with this JavaScript:
If you don't have
Globalize
globally available then you could:to make it globally available or just add it to the template's namespace manually:
Demos:
Globalize
throughwindow.Globalize
..Globalize
through the_.template
parameters..There's really nothing special about the Underscore templates, the stuff inside
<%= %>
is just JavaScript code that ends up wrapped in awith
block. You can even see the function's source by looking at thesource
property on the returned template function:and you'll see some fairly simple (if ugly) JavaScript like this:
That
+ (Globalize.mangle(pancakes) )+
bit is what<%= Globalize.mangle(pancakes) %>
gets turned into. No magic, no special parsing of the contents of<%= ... %>
, just a simpleminded (but effective) conversion to JavaScript.