-
Notifications
You must be signed in to change notification settings - Fork 31
/
stringTemplateEngine.js
57 lines (45 loc) · 1.74 KB
/
stringTemplateEngine.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
define(["knockout"], function(ko) {
//define a template source that tries to key into an object first to find a template string
var templates = {},
data = {},
engine = new ko.nativeTemplateEngine();
ko.templateSources.stringTemplate = function(template) {
this.templateName = template;
};
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) {
var template = templates[this.templateName];
if (typeof (template) === "undefined") {
throw Error("Template not found: " + this.templateName);
}
return template;
}
templates[this.templateName] = value;
}
});
engine.makeTemplateSource = function(template, doc) {
var elem;
if (typeof template === "string") {
elem = (doc || document).getElementById(template);
if (elem) {
return new ko.templateSources.domElement(elem);
}
return new ko.templateSources.stringTemplate(template);
}
else if (template && (template.nodeType == 1) || (template.nodeType == 8)) {
return new ko.templateSources.anonymousTemplate(template);
}
};
//make the templates accessible
ko.templates = templates;
//make this new template engine our default engine
ko.setTemplateEngine(engine);
});