-- ********************************************************************** -- * Html page renderer -- * -- * version 0.1 -- * -- * (c) 2005 Hi-Project Ltd. -- ********************************************************************** require "webserver.encoding" require "common.errors" module "htemplate" local TK_VARNAME = "([%w_']*)" -- variable name pattern eg. my_funny_varname local TK_PREFIX = "%w*:" local TK_START = "{$" local TK_END = "$}" local PATTERNS = { parameter = "", -- parses function input parameters variable = "VAR:", checkbox = "CB:" } -- removes the unused tokens function cleanup_buffer(htemp) if htemp == nil then return nil end table.foreach(PATTERNS, function(k,v) local w = "" local prefix = v for w in string.gfind(htemp, TK_START..prefix..TK_VARNAME..TK_END) do htemp = string.gsub(htemp, TK_START..prefix..w..TK_END, "") end end) return htemp end -- parses global variable {$VAR:xxx$} function parse_global_variables(htemp) if htemp==nil then return nil end local w = "" for w in string.gfind(htemp, TK_START..PATTERNS.variable..TK_VARNAME..TK_END) do htemp = string.gsub(htemp, TK_START..PATTERNS.variable..w..TK_END, str_encode(getfenv()[w])) end return htemp end -- parses checkbox {$CB:xxx$} function parse_checkbox(htemp,name,value) if htemp==nil then return nil end if value~="0" and value~="" then htemp = string.gsub(htemp, name, "checked") else htemp = string.gsub(htemp, name, " ") end return htemp end -- -- API call -- Template Buffer renderer -- function parsebuffer(ht,func_result) if ht==nil then LUNAERROR.seterrorbyname("TEMPLATE_NOTFOUND") return LUNAERROR.geterrormessage() end func_result = table_encode(func_result) or {} table.foreach(func_result, function(k,v) if k then -- parameter ht = string.gsub(ht, TK_START..k..TK_END, v) -- checkbox if string.gfind(ht,TK_START..PATTERNS.checkbox..k..TK_END) then ht = parse_checkbox(ht,TK_START..PATTERNS.checkbox..k..TK_END,v) end end end) -- global vars ht = parse_global_variables(ht) ht = cleanup_buffer(ht) if ht==nil then LUNAERROR.seterrorbyname("TEMPLATE_NOTPARSED") return LUNAERROR.geterrormessage() else return ht end end -------------------------------------------------------------------------- -- Initialization -------------------------------------------------------------------------- LUNAERROR.adderror("TEMPLATE_NOTFOUND", 101, "HTML TEMPLATE NOT FOUND", "EN") LUNAERROR.adderror("TEMPLATE_NOTPARSED", 102, "HTML TEMPLATE PARSING ERROR", "EN")