One Level Up
Top Level
a.lua - lemplate
Functions defined
Source code
- local gsub = ngx.re.gsub
- local concat = table.concat
- local type = type
- local math_floor = math.floor
- local table_maxn = table.maxn
- local _M = {
- version = '0.01'
- }
- local template_map = {}
- local function tt2_true(v)
- return v and v ~= 0 and v ~= "" and v ~= '0'
- end
- local function tt2_not(v)
- return not v or v == 0 or v == "" or v == '0'
- end
- local context_meta = {}
- function context_meta.plugin(context, name, args)
- if name == "iterator" then
- local list = args[1]
- local count = table_maxn(list)
- return { list = list, count = 1, max = count - 1, index = 0, size = count, first = true, last = false, prev = "" }
- else
- return error("unknown iterator: " .. name)
- end
- end
- function context_meta.process(context, file)
- local f = template_map[file]
- if not f then
- return error("file error - " .. file .. ": not found")
- end
- return f(context)
- end
- function context_meta.include(context, file)
- local f = template_map[file]
- if not f then
- return error("file error - " .. file .. ": not found")
- end
- return f(context)
- end
- context_meta = { __index = context_meta }
- local function stash_get(stash, k)
- local v
- if type(k) == "table" then
- v = stash
- for i = 1, #k, 2 do
- local key = k[i]
- local typ = k[i + 1]
- if type(typ) == "table" then
- local value = v[key]
- if type(value) == "function" then
- return value()
- end
- if value then
- return value
- end
- if key == "size" then
- if type(v) == "table" then
- return #v
- else
- return 1
- end
- else
- return error("virtual method " .. key .. " not supported")
- end
- end
- if type(key) == "number" and key == math_floor(key) and key >= 0 then
- key = key + 1
- end
- if type(v) ~= "table" then
- return nil
- end
- v = v[key]
- end
- else
- v = stash[k]
- end
- if type(v) == "function" then
- return v()
- end
- return v
- end
- local function stash_set(stash, k, v, default)
- if default then
- local old = stash[k]
- if old == nil then
- stash[k] = v
- end
- else
- stash[k] = v
- end
- end
- function _M.process(file, params)
- local stash = params
- local context = {
- stash = stash,
- filter = function (bits, name, params)
- local s = concat(bits)
- if name == "html" then
- s = gsub(s, "&", '&', "jo")
- s = gsub(s, "<", '<', "jo");
- s = gsub(s, ">", '>', "jo");
- s = gsub(s, '"', '"', "jo");
- return s
- end
- end
- }
- context = setmetatable(context, context_meta)
- local f = template_map[file]
- if not f then
- return error("file error - " .. file .. ": not found")
- end
- return f(context)
- end
- template_map['tmpQQS_k.tt2'] = function (context)
- if not context then
- return error("Lemplate function called without context\n")
- end
- local stash = context.stash
- local output = {}
- local i = 0
- i = i + 1 output[i] = 'Hello, '
- i = i + 1 output[i] = stash_get(stash, 'world')
- i = i + 1 output[i] = '!\n'
- return output
- end
- return _M
One Level Up
Top Level