Advertisement
Guest User

template_filter.lua

a guest
Jul 8th, 2015
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.40 KB | None | 0 0
  1.  
  2.     require 'inifile'
  3.  
  4.     if ngx.header.content_type == "text/html" then
  5.         local file = ngx.var.request_filename
  6.         local dir, cnt, err = ngx.re.gsub(file, "[^/]+$", "")
  7.         local ini = dir .. "template.ini"
  8.  
  9.         local fh = io.open(ini, "r")
  10.         if fh ~= nil then
  11.             io.close(fh)
  12.  
  13.             if ngx.get_phase() == "header_filter" then
  14.                 ngx.header.content_length = nil
  15.  
  16.             elseif ngx.get_phase() == "body_filter" then
  17.                 local tmpl = ngx.ctx.template_variables
  18.                 local buff = ngx.ctx.chunk_buffer
  19.                 local matched = 0
  20.                 local last_chunk = ngx.arg[2]
  21.                
  22.                 if not tmpl then
  23.                     tmpl = inifile.parse(ini, false)
  24.                     ngx.ctx.template_variables = tmpl
  25.                 end
  26.                 if buff then
  27.                     ngx.arg[1] = buff .. ngx.arg[1]
  28.                 end
  29.  
  30.                 if not last_chunk then
  31.                     grp, err = ngx.re.match(ngx.arg[1], "<(!(-(-(\\{([^\\}]+(\\}(-(-(>)?)?)?)?)?)?)?)?)?$")
  32.                     if err then
  33.                         ngx.log(ngx.ERR, "re.match error: ", err)
  34.                     else
  35.                         ngx.log(ngx.DEBUG, "possible chunked template tag: ", grp[0])
  36.                         matched = 1
  37.                     end
  38.                 end
  39.                 if not last_chunk and matched then
  40.                     buff = ngx.arg[1]
  41.                     ngx.arg[1] = nil
  42.                 else
  43.                     for tmplvar, tmplstr in pairs(tmpl["html"]) do
  44.                         local str, cnt, err = ngx.re.gsub(ngx.arg[1], "<!--\\{" .. tmplvar .. "\\}-->", tmplstr)
  45.                         if str then
  46.                             ngx.arg[1] = str
  47.                         else
  48.                             ngx.log(ngx.ERR, "re.gsub error: ", err)
  49.                         end
  50.                     end
  51.                 end
  52.                
  53.                 ngx.ctx.chunk_buffer = buff
  54.             end
  55.         end
  56.     end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement