-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathtemplate.lua
58 lines (53 loc) · 1.2 KB
/
template.lua
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
local template = {}
function template.escape(data)
return tostring(data or ''):gsub("[\">/<'&]", {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
["/"] = "/"
})
end
function template.print(data, args, callback)
local callback = callback or print
local function exec(data)
if type(data) == "function" then
local args = args or {}
setmetatable(args, { __index = _G })
setfenv(data, args)
data(exec)
else
callback(tostring(data or ''))
end
end
exec(data)
end
function template.parse(data, minify)
local str =
"return function(_)" ..
"function __(...)" ..
"_(require('template').escape(...))" ..
"end " ..
"_[=[" ..
data:
gsub("[][]=[][]", ']=]_"%1"_[=['):
gsub("<%%=", "]=]_("):
gsub("<%%", "]=]__("):
gsub("%%>", ")_[=["):
gsub("<%?", "]=] "):
gsub("%?>", " _[=[") ..
"]=] " ..
"end"
if minify then
str = str:
gsub("^[ %s]*", ""):
gsub("[ %s]*$", ""):
gsub("%s+", " ")
end
return str
end
function template.compile(...)
return loadstring(template.parse(...))()
end
return template