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,20 +393,18 @@ 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 output = {} local fn = assert(loadstring(str))
local echo = function(str) table.insert(output, str) end return function(...)
assert(loadstring(str))(echo, unpack(vals)) local output = {}
return table.concat(map(output, tostring)) local echo = function(str) table.insert(output, str) end
fn(echo, ...)
return table.concat(map(output, tostring))
end
end end
@ -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