Changed lovebird.template() to return compiled template

lovebird.template() now returns the compiled template as a function
rather than the result of the template. To make this possible the
parameters and usage of the function has also changed.
This commit is contained in:
rxi 2014-04-13 15:48:24 +01:00
parent fe2e607baa
commit 188d052d34

View File

@ -393,21 +393,19 @@ function lovebird.init()
end end
function lovebird.template(str, env) function lovebird.template(str, params)
env = env or {} params = params and ("," .. params) or ""
local keys, vals = {}, {}
for k, v in pairs(env) do
table.insert(keys, k)
table.insert(vals, v)
end
local f = function(x) return string.format(" echo(%q)", x) end local f = function(x) return string.format(" echo(%q)", x) end
str = ("?>"..str.."<?lua"):gsub("%?>(.-)<%?lua", f) str = ("?>"..str.."<?lua"):gsub("%?>(.-)<%?lua", f)
str = "local echo, " .. table.concat(keys, ",") .. " = ..." .. str str = "local echo " .. params .. " = ..." .. str
local fn = assert(loadstring(str))
return function(...)
local output = {} local output = {}
local echo = function(str) table.insert(output, str) end local echo = function(str) table.insert(output, str) end
assert(loadstring(str))(echo, unpack(vals)) fn(echo, ...)
return table.concat(map(output, tostring)) return table.concat(map(output, tostring))
end end
end
function lovebird.parseurl(url) function lovebird.parseurl(url)
@ -501,7 +499,7 @@ function lovebird.onrequest(req, client)
xpcall(function() xpcall(function()
str = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" .. str = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" ..
lovebird.template(lovebird.pages[page], lovebird.template(lovebird.pages[page],
{ lovebird = lovebird, req = req }) "lovebird, req")(lovebird, req)
end, lovebird.onerror) end, lovebird.onerror)
return str return str
end end