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