-
Notifications
You must be signed in to change notification settings - Fork 8
/
string-template-engine.js
66 lines (52 loc) · 1.82 KB
/
string-template-engine.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
//https://github.com/rniemeyer/SamplePresentation/blob/master/js/stringTemplateEngine.js
import ko from "knockout";
//define a template source that simply treats the template name as its content
var templates = {},
data = {},
engine = new ko.nativeTemplateEngine();
ko.templateSources.stringTemplate = function(template) {
this.templateName = template;
};
ko.templateSources.stringTemplate.caseInsensitive = false;
ko.utils.extend(ko.templateSources.stringTemplate.prototype, {
data: function(key, value) {
data[this.templateName] = data[this.templateName] || {};
if(arguments.length === 1) {
return data[this.templateName][key];
}
data[this.templateName][key] = value;
},
text: function(value) {
if(arguments.length === 0) {
return templates[this.templateName];
}
templates[this.templateName] = value;
}
});
engine.makeTemplateSource = function(template, templateDocument) {
// Named template
if (typeof template == "string") {
templateDocument = templateDocument || document;
var elem = templateDocument.getElementById(template);
if (elem) {
return new ko.templateSources.domElement(elem);
}
var templateName = template;
if (ko.templateSources.stringTemplate.caseInsensitive) {
templateName = templateName.toLowerCase();
}
if (ko.templates[templateName]) {
return new ko.templateSources.stringTemplate(templateName);
}
throw new Error("Cannot find template with ID " + template);
} else if ((template.nodeType == 1) || (template.nodeType == 8)) {
// Anonymous template
return new ko.templateSources.anonymousTemplate(template);
} else {
throw new Error("Unknown template type: " + template);
}
};
//make the templates accessible
ko.templates = templates;
//make this new template engine our default engine
ko.setTemplateEngine(engine);