5 A template parser supporting includes, translations, Lua code blocks
6 and more. It can be used either as a compiler or as an interpreter.
11 Copyright 2008 Steven Barth <steven@midlink.org>
13 Licensed under the Apache License, Version 2.0 (the "License");
14 you may not use this file except in compliance with the License.
15 You may obtain a copy of the License at
17 http://www.apache.org/licenses/LICENSE-2.0
19 Unless required by applicable law or agreed to in writing, software
20 distributed under the License is distributed on an "AS IS" BASIS,
21 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22 See the License for the specific language governing permissions and
23 limitations under the License.
27 local fs = require"luci.fs"
28 local sys = require "luci.sys"
29 local util = require "luci.util"
30 local table = require "table"
31 local string = require "string"
32 local config = require "luci.config"
33 local coroutine = require "coroutine"
35 local tostring, pairs, loadstring = tostring, pairs, loadstring
36 local setmetatable, loadfile = setmetatable, loadfile
37 local getfenv, setfenv = getfenv, setfenv
38 local assert, type, error = assert, type, error
40 --- LuCI template library.
41 module "luci.template"
43 config.template = config.template or {}
45 viewdir = config.template.viewdir or util.libpath() .. "/view"
46 compiledir = config.template.compiledir or util.libpath() .. "/view"
50 -- memory: Always compile, do not save compiled files, ignore precompiled
51 -- file: Compile on demand, save compiled files, update precompiled
52 compiler_mode = config.template.compiler_mode or "memory"
55 -- Define the namespace for template modules
56 context = util.threadlocal()
59 include = function(name) Template(name):render(getfenv(2)) end,
62 --- Manually compile a given template into an executable Lua function
63 -- @param template LuCI template
64 -- @return Lua template function
65 function compile(template)
68 -- Search all <% %> expressions
69 local function expr_add(ws1, skip1, command, skip2, ws2)
70 table.insert(expr, command)
71 return ( #skip1 > 0 and "" or ws1 ) ..
72 "<%" .. tostring(#expr) .. "%>" ..
73 ( #skip2 > 0 and "" or ws2 )
76 -- Save all expressiosn to table "expr"
77 template = template:gsub("(%s*)<%%(%-?)(.-)(%-?)%%>(%s*)", expr_add)
79 local function sanitize(s)
84 -- Escape and sanitize all the template (all non-expressions)
85 template = sanitize(template)
87 -- Template module header/footer declaration
88 local header = 'write("'
91 template = header .. template .. footer
94 local r_include = '")\ninclude("%s")\nwrite("'
95 local r_i18n = '"..translate("%1","%2").."'
96 local r_i18n2 = '"..translate("%1", "").."'
97 local r_pexec = '"..(%s or "").."'
98 local r_exec = '")\n%s\nwrite("'
100 -- Parse the expressions
101 for k,v in pairs(expr) do
102 local p = v:sub(1, 1)
103 v = v:gsub("%%", "%%%%")
106 re = r_include:format(sanitize(string.sub(v, 2)))
109 re = sanitize(v):gsub(":(.-) (.*)", r_i18n)
111 re = sanitize(v):gsub(":(.+)", r_i18n2)
114 re = r_pexec:format(v:sub(2))
118 re = r_exec:format(v)
120 template = template:gsub("<%%"..tostring(k).."%%>", re)
123 return loadstring(template)
126 --- Render a certain template.
127 -- @param name Template name
128 -- @param scope Scope to assign to template (optional)
129 function render(name, scope)
130 return Template(name):render(scope or getfenv(2))
135 Template = util.class()
137 -- Shared template cache to store templates in to avoid unnecessary reloading
138 Template.cache = setmetatable({}, {__mode = "v"})
141 -- Constructor - Reads and compiles the template on-demand
142 function Template.__init__(self, name)
143 local function _encode_filename(str)
145 local function __chrenc( chr )
146 return "%%%02x" % string.byte( chr )
149 if type(str) == "string" then
151 "([^a-zA-Z0-9$_%-%.%+!*'(),])",
159 self.template = self.cache[name]
162 -- Create a new namespace for this template
163 self.viewns = {sink=self.sink}
165 -- Copy over from general namespace
166 util.update(self.viewns, viewns)
167 if context.viewns then
168 util.update(self.viewns, context.viewns)
171 -- If we have a cached template, skip compiling and loading
172 if self.template then
176 -- Enforce cache security
177 local cdir = compiledir .. "/" .. sys.process.info("uid")
180 local sourcefile = viewdir .. "/" .. name .. ".htm"
181 local compiledfile = cdir .. "/" .. _encode_filename(name) .. ".lua"
184 if compiler_mode == "file" then
185 local tplmt = fs.mtime(sourcefile)
186 local commt = fs.mtime(compiledfile)
188 if not fs.mtime(cdir) then
190 fs.chmod(fs.dirname(cdir), "a+rxw")
193 -- Build if there is no compiled file or if compiled file is outdated
194 if ((commt == nil) and not (tplmt == nil))
195 or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
197 source, err = fs.readfile(sourcefile)
200 local compiled, err = compile(source)
202 fs.writefile(compiledfile, util.get_bytecode(compiled))
203 fs.chmod(compiledfile, "a-rwx,u+rw")
204 self.template = compiled
208 sys.process.info("uid") == fs.stat(compiledfile, "uid")
209 and fs.stat(compiledfile, "mode") == "rw-------",
210 "Fatal: Cachefile is not sane!"
212 self.template, err = loadfile(compiledfile)
215 elseif compiler_mode == "memory" then
217 source, err = fs.readfile(sourcefile)
219 self.template, err = compile(source)
224 -- If we have no valid template throw error, otherwise cache the template
225 if not self.template then
228 self.cache[name] = self.template
233 -- Renders a template
234 function Template.render(self, scope)
235 scope = scope or getfenv(2)
237 -- Save old environment
238 local oldfenv = getfenv(self.template)
240 -- Put our predefined objects in the scope of the template
241 util.resfenv(self.template)
242 util.updfenv(self.template, scope)
243 util.updfenv(self.template, self.viewns)
245 -- Now finally render the thing
246 local stat, err = util.copcall(self.template)
248 setfenv(self.template, oldfenv)
249 error("Error in template %s: %s" % {self.name, chunk})
253 setfenv(self.template, oldfenv)