-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
48 lines (38 loc) · 985 Bytes
/
index.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
module.exports = Block
function Block(string) {
if (!(this instanceof Block))
return new Block(string)
this.string = string
}
Block.prototype.locals =
Block.prototype.local = function (name, value) {
if (typeof name === 'object')
Object.keys(name).forEach(function (key) {
this.replace(key, name[key])
}, this)
else
this.replace(name, value)
return this
}
Block.prototype.replace = function (key, value) {
this.string = replace(this.string, key, value)
return this
}
Block.prototype.render = function (locals) {
if (!locals)
return this.string
var string = this.string
Object.keys(locals).forEach(function (key) {
string = replace(string, key, locals[key])
})
return string
}
function replace(string, key, value) {
return string.replace(
new RegExp('\\{\\{\\s*' + escapeRegExp(key) + '\\s*\\}\\}', 'g'),
value || ''
)
}
function escapeRegExp(str) {
return str.replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1')
}