-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathtemplate.lua
More file actions
75 lines (70 loc) · 1.56 KB
/
template.lua
File metadata and controls
75 lines (70 loc) · 1.56 KB
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
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 env = args or {}
setmetatable(env, { __index = _G })
if _ENV then -- Lua 5.2+
local wrapper, err = load([[
return function(_ENV, exec)
local f = ...
f(exec)
end
]], "wrapper", "t", env)
if not wrapper then
error(err)
end
wrapper()(env, exec, data)
else
setfenv(data, env)
data(exec)
end
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(...)
local f, err = loadstring(template.parse(...))
if err then
error(err)
end
return f()
end
return template