the "mkws-paragraphs" Handlebars helper now accepts an optional second
[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 = undefined;
17   if (!count || count > obj.length) count = obj.length;
18
19   for (var i = 0; i < count; i++) {
20     acc.push('<p>', obj[i].replace(/\[[0-9,]+\]/g, ''), '</p>');
21   }
22   return acc.join('');
23 });
24
25
26 Handlebars.registerHelper('mkws-translate', function(s) {
27   return mkws.M(s);
28 });
29
30
31 // We need {{mkws-attr '@name'}} because Handlebars can't parse {{@name}}
32 Handlebars.registerHelper('mkws-attr', function(attrName) {
33   return this[attrName];
34 });
35
36
37 /*
38  * Use as follows: {{#mkws-if-any NAME1 having="NAME2"}}
39  * Applicable when NAME1 is the name of an array
40  * The guarded code runs only if at least one element of the NAME1
41  * array has a subelement called NAME2.
42  */
43 Handlebars.registerHelper('mkws-if-any', function(items, options) {
44   var having = options.hash.having;
45   for (var i in items) {
46     var item = items[i]
47     if (!having || item[having]) {
48       return options.fn(this);
49     }
50   }
51   return "";
52 });
53
54
55 Handlebars.registerHelper('mkws-first', function(items, options) {
56   var having = options.hash.having;
57   for (var i in items) {
58     var item = items[i]
59     if (!having || item[having]) {
60       return options.fn(item);
61     }
62   }
63   return "";
64 });
65
66
67 Handlebars.registerHelper('mkws-commaList', function(items, options) {
68   var out = "";
69
70   for (var i in items) {
71     if (i > 0) out += ", ";
72     out += options.fn(items[i])
73   }
74
75   return out;
76 });
77
78
79 Handlebars.registerHelper('mkws-index1', function(obj) {
80   return obj.data.index + 1;
81 });