-
Notifications
You must be signed in to change notification settings - Fork 0
/
handlebars-helpers.js
74 lines (64 loc) · 1.91 KB
/
handlebars-helpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*globals Handlebars, moment, jQuery */
(function($) {
// Get the current url
Handlebars.registerHelper('windowLocation', function(place_id) {
return window.location;
});
// Change new lines to <br> tags. This one is better than Swag.
Handlebars.registerHelper('nlToBr', function(str) {
if (str) {
str = Handlebars.Utils.escapeExpression(str);
return new Handlebars.SafeString(str.replace(/\r?\n|\r/g, '<br>'));
} else {
return str;
}
});
// Date and time ------------------------------------------------------------
Handlebars.registerHelper('formatDateTime', function(datetime, format) {
if (datetime) {
return moment(datetime).format(format);
}
return '';
});
Handlebars.registerHelper('fromNow', function(datetime) {
if (datetime) {
return moment(datetime).fromNow();
}
return '';
});
// Iteration ----------------------------------------------------------------
Handlebars.registerHelper('times', function(n, options) {
var accum = '', i;
for(i = 0; i < n; ++i){
accum += options.fn(i);
}
return accum;
});
Handlebars.registerHelper('range', function(from, to, options) {
// Range is INCLUSIVE of the ends. Useful for things like
// pagination links.
var accum = '', i;
for(i = from; i <= to; i++){
accum += options.fn(i);
}
return accum;
});
// HTML ---------------------------------------------------------------------
Handlebars.registerHelper('select', function(value, options) {
var $el = $('<div/>').html(options.fn(this)),
selectValue = function(v) {
$el.find('[value="'+v+'"]').attr({
checked: 'checked',
selected: 'selected'
});
};
if ($.isArray(value)) {
jQuery.each(value, function(i, v) {
selectValue(v);
});
} else {
selectValue(value);
}
return $el.html();
});
}(jQuery));