forked from ellej/lua-template
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.lua
More file actions
113 lines (95 loc) · 2.27 KB
/
template.lua
File metadata and controls
113 lines (95 loc) · 2.27 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
local template = {}
function template.escape(data)
return tostring(data == nil and "" or data):gsub("[\">/<'&]", {
["&"] = "&",
["<"] = "<",
[">"] = ">",
['"'] = """,
["'"] = "'",
["/"] = "/"
})
end
-- If it's lua 5.2+, _ENV will appears
local wrapper_fn do
if _ENV then
local wrapper, err = load(
[[return function(_ENV,exec,...) local f=...; f(exec, _ENV); end]],
"wrapper", "t"
)
if not wrapper then error(err) end
wrapper_fn = wrapper()
end
end
function template.print(data, args, callback)
local callback = callback or print
local env = args or {}
setmetatable(env, { __index = _G })
local function exec(ins)
if type(ins) ~= "function" then
return callback(tostring(ins == nil and "" or ins))
end
-- if type(data) == "function"
-- Lua 5.2+ , use call delegate
if wrapper_fn then
return wrapper_fn(env, exec, ins)
end
-- Lua 5.1
setfenv(ins, env)
ins(exec)
end
exec(data)
end
local template_entry do
local s = "function(_"
if not _ENV
then s = s .. ') '
else s = s .. ",_ENV) "
end
template_entry = s
end
function template.parse(data, minify)
local str =
"return " .. template_entry ..
"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
--[[
`loadstring` was deprecated since 5.2, use `load` instead
(see: https://www.lua.org/manual/5.2/manual.html#8.2)
]]--
local loadstring = loadstring or function(str, chkn)
return load(str, chkn or str, 't') -- We will pass _ENV manually
end
function template.compile(...)
local f, err = loadstring(template.parse(...))
if err then error(err); end
return f()
end
function template.render(data, args)
local parts = {}
local i = 0
template.print(data, args, function(p)
i = i + 1
parts[i] = p
end)
return table.concat(parts)
end
return template