forked from sociocracyforall/wp-sofatime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtemplate.js
50 lines (42 loc) · 1.54 KB
/
template.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
export default function jsontemplate(document, template, data) {
const resultFragment = document.createDocumentFragment();
processOneOrMoreRules(resultFragment, template, data);
return resultFragment;
};
function processOneOrMoreRules(parentNode, ruleOrRules, data) {
if (Array.isArray(ruleOrRules)) {
ruleOrRules.map(function (rule) { processRule(parentNode, rule, data); });
} else {
processRule(ruleOrRules);
}
}
function processRule(parentNode, rule, data) {
const contents = data[rule.key];
applyRule(parentNode, rule, contents);
}
function applyRule(parentNode, rule, contents) {
if (Array.isArray(contents)) {
contents.map(function (item) { applyRule(parentNode, rule, item); });
} else {
let node = undefined;
if (rule.text === true) {
node = parentNode.ownerDocument.createTextNode(contents);
} else { // This should be an element rule, but we should specify and test
// this....
node = parentNode.ownerDocument.createElement(rule.element);
if (rule.attributes !== undefined) {
if (typeof rule.attributes === 'string') {
node.setAttribute(rule.attributes, contents[rule.attributes]);
} else { // rule.attributes should be a "simple" object
Object.keys(rule.attributes).map(function (name) {
node.setAttribute(rule.attributes[name], contents[name]);
});
}
}
if (rule.children !== undefined) {
processOneOrMoreRules(node, rule.children, contents);
}
}
parentNode.appendChild(node);
}
}