Handlebars Helpers vs String Utilities
You can register a template helper, or implement your own string utility. Which works best depends on your goals.
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.3.0/handlebars.min.js"></script>
<template id="template-helper">
<p>The date is {{#date now}}{{/date}}</p>
</template>
<template id="template-tostring">
<p>The date is {{now}}</p>
</template>
<h1>registerHelper()</h1>
<div id="helper"></div>
<h2>toString()</h2>
<div id="tostring"></div>
CSS
body {
font: 0.9em Arial, Helvetica, sans-serif;
}
JavaScript
// Registers a simple "date" template helper.
Handlebars.registerHelper( "date", function( date ) {
return date.toLocaleString();
});
// A lazy-evaluating helper class that does esentially the same
// thing as the registered helper above.
function DateString( date ) {
this.toString = function() {
return date.toString();
};
}
$(function() {
// Compiles the two templates.
var helperTemplate = Handlebars.compile( $( "#template-helper" ).html() ),
toStringTemplate = Handlebars.compile( $( "#template-tostring" ).html() );
// Renders the two templates.
$( "#helper" ).html( helperTemplate( { now: new Date() } ) );
$( "#tostring" ).html( toStringTemplate( { now: new DateString( new Date() ) } ) );
});