Simplify handling of optional count argument.
[mkws-moved-to-github.git] / src / mkws-handlebars.js
1 // Handlebars helpers
2
3 Handlebars.registerHelper('mkws-json', function(obj) {
4   return $.toJSON(obj);
5 });
6
7
8 // This is intended to handle paragraphs from Wikipedia, hence the
9 // rather hacky code to remove numbered references.
10 //
11 Handlebars.registerHelper('mkws-paragraphs', function(obj, count) {
12   var acc = [];
13
14   // For some reason, Handlebars provides the value
15   // {"hash":{},"data":{}} for undefined parameters
16   if (count.hasOwnProperty('hash') || count == 0 || count > obj.length) {
17     count = obj.length;
18   }
19
20   for (var i = 0; i < count; i++) {
21     acc.push('<p>', obj[i].replace(/\[[0-9,]+\]/g, ''), '</p>');
22   }
23   return acc.join('');
24 });
25
26
27 Handlebars.registerHelper('mkws-translate', function(s) {
28   return mkws.M(s);
29 });
30
31
32 // We need {{mkws-attr '@name'}} because Handlebars can't parse {{@name}}
33 Handlebars.registerHelper('mkws-attr', function(attrName) {
34   return this[attrName];
35 });
36
37
38 /*
39  * Use as follows: {{#mkws-if-any NAME1 having="NAME2"}}
40  * Applicable when NAME1 is the name of an array
41  * The guarded code runs only if at least one element of the NAME1
42  * array has a subelement called NAME2.
43  */
44 Handlebars.registerHelper('mkws-if-any', function(items, options) {
45   var having = options.hash.having;
46   for (var i in items) {
47     var item = items[i]
48     if (!having || item[having]) {
49       return options.fn(this);
50     }
51   }
52   return "";
53 });
54
55
56 Handlebars.registerHelper('mkws-first', function(items, options) {
57   var having = options.hash.having;
58   for (var i in items) {
59     var item = items[i]
60     if (!having || item[having]) {
61       return options.fn(item);
62     }
63   }
64   return "";
65 });
66
67
68 Handlebars.registerHelper('mkws-commaList', function(items, options) {
69   var out = "";
70
71   for (var i in items) {
72     if (i > 0) out += ", ";
73     out += options.fn(items[i])
74   }
75
76   return out;
77 });
78
79
80 Handlebars.registerHelper('mkws-index1', function(obj) {
81   return obj.data.index + 1;
82 });