tray/src/messenger/webim/js/source/handlebars_helpers.js
Dmitriy Simushev 83636a02ef Add several Handlebars helpers
Add 'apply', 'formatTime' and 'nl2br' Handlebars helpers.
Also add QUnit tests for 'apply' helper.
2013-03-13 15:32:42 +00:00

75 lines
2.2 KiB
JavaScript

/**
* @preserve This file is part of Mibew Messenger project.
* http://mibew.org
*
* Copyright (c) 2005-2011 Mibew Messenger Community
* License: http://mibew.org/license.php
*/
/**
* Register 'apply' Handlebars helper.
*
* This helper provide an ability to apply several helpers to single Handlebars
* expression
*/
Handlebars.registerHelper('apply', function(text, helpers) {
var result = text;
var validHelperName = /^[0-9A-z_]+$/;
helpers = helpers.split(/\s*,\s*/);
for (var prop in helpers) {
if (! helpers.hasOwnProperty(prop) ||
! validHelperName.test(helpers[prop])) {
continue;
}
if (typeof Handlebars.helpers[helpers[prop]] != 'function') {
throw new Error(
"Unregistered helper '" + helpers[prop] + "'!"
);
}
result = Handlebars.helpers[helpers[prop]](result);
}
return new Handlebars.SafeString(result);
});
/**
* Register 'formatTime' Handlebars helper.
*
* This helper takes unix timestamp as argument and return time in "HH:MM:SS"
* format
*/
Handlebars.registerHelper('formatTime', function(unixTimestamp){
var d = new Date(unixTimestamp * 1000);
// Get time parts
var hours = d.getHours().toString();
var minutes = d.getMinutes().toString();
var seconds = d.getSeconds().toString();
// Add leading zero if needed
hours = hours > 10 ? hours : '0' + hours;
minutes = minutes > 10 ? minutes : '0' + minutes;
seconds = seconds > 10 ? seconds : '0' + seconds;
// Build result string
return hours + ':' + minutes + ':' + seconds;
});
/**
* Register 'urlReplace' Handlebars helper.
*
* This helper serch URLs and replace them by 'a' tag
*/
Handlebars.registerHelper('urlReplace', function(text) {
return new Handlebars.SafeString(
text.replace(
/((?:https?|ftp):\/\/\S*)/g,
'<a href="$1" target="_blank">$1</a>'
)
);
});
/**
* Register 'nl2br' Handlebars helper.
*
* This helper replace all new line characters (\n) by 'br' tags
*/
Handlebars.registerHelper('nl2br', function(text) {
return new Handlebars.SafeString(text.replace(/\n/g, "<br/>"));
});