-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjshtml.js
79 lines (64 loc) · 2.37 KB
/
jshtml.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
67
68
69
70
71
72
73
74
75
76
77
78
79
// JSHTML v4.0.0 MIT/GPL2 @jon_neal
(function (global) {
function Document() {}
Document.prototype.write = Array.prototype.push;
Document.prototype.close = function () { return Array.prototype.splice.call(this, 0, this.length).join(""); };
function escapeJS(str) {
return str.replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r');
}
function TemplateWalk(str, chars) {
// check for the opening delimiters and init our array buffer
var index = str.indexOf(chars.START_PROP), buffer = '', helper;
// if the opening delimiters are encountered
if (index > -1) {
// add to the buffer the contents before the opening delimiters
buffer += 'document.write("' + escapeJS(str.substr(0, index)) + '");';
// move the string to after the opening delimiters
str = str.substr(index + chars.START_PROP.length);
// get the helper character of the string
helper = str.substr(0, 1);
// get the index of the closing delimiters
index = str.indexOf(chars.END_PROP);
// if the closing delimiters are encountered
if (index > -1) {
if (helper == "=") {
// add to the buffer the return of the helper function
buffer += 'document.write(' + str.substr(helper.length, index - helper.length) + ');';
// move the string to after the closing delimiters
str = str.substr(index + chars.END_PROP.length);
// add to the buffer the return of this function
buffer += TemplateWalk(str, chars);
} else {
// add to the buffer the contents before the closing delimiters
buffer += str.substr(0, index);
// add to the buffer the return of this function
buffer += TemplateWalk(str.substr(index + chars.END_PROP.length), chars);
}
}
}
// if the opening delimiters are not encountered
else {
buffer += 'document.write("' + escapeJS(str) + '");';
}
// return the buffer
return buffer;
}
function JSHTML() {
var
instance = this;
instance.template = '';
instance.context = {};
instance.render = function () {
return Function(
'scope',
'document',
'with(scope){' + TemplateWalk(instance.template, instance.delimiters) + '}return document;'
).call(instance, instance.context, new Document).close();
};
instance.delimiters = {
'START_PROP': '<%',
'END_PROP': '%>'
};
}
global.JSHTML = JSHTML;
})(this);