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.
26 module("luci.template", package.seeall)
28 require("luci.config")
33 luci.config.template = luci.config.template or {}
35 viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
36 compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
40 -- none: Never compile, only use precompiled data from files
41 -- memory: Always compile, do not save compiled files, ignore precompiled
42 -- file: Compile on demand, save compiled files, update precompiled
43 compiler_mode = luci.config.template.compiler_mode or "memory"
46 -- Define the namespace for template modules
47 context = luci.util.threadlocal()
50 include = function(name) Template(name):render(getfenv(2)) end,
53 -- Compiles a given template into an executable Lua module
54 function compile(template)
55 -- Search all <% %> expressions (remember: Lua table indexes begin with #1)
56 local function expr_add(ws1, skip1, command, skip2, ws2)
57 table.insert(expr, command)
58 return ( #skip1 > 0 and "" or ws1 ) ..
59 "<%" .. tostring(#expr) .. "%>" ..
60 ( #skip2 > 0 and "" or ws2 )
63 -- As "expr" should be local, we have to assign it to the "expr_add" scope
65 luci.util.extfenv(expr_add, "expr", expr)
67 -- Save all expressiosn to table "expr"
68 template = template:gsub("(%s*)<%%(%-?)(.-)(%-?)%%>(%s*)", expr_add)
70 local function sanitize(s)
71 s = luci.util.escape(s)
72 s = luci.util.escape(s, "'")
73 s = luci.util.escape(s, "\n")
77 -- Escape and sanitize all the template (all non-expressions)
78 template = sanitize(template)
80 -- Template module header/footer declaration
81 local header = "write('"
84 template = header .. template .. footer
87 local r_include = "')\ninclude('%s')\nwrite('"
88 local r_i18n = "'..translate('%1','%2')..'"
89 local r_i18n2 = "'..translate('%1', '')..'"
90 local r_pexec = "'..(%s or '')..'"
91 local r_exec = "')\n%s\nwrite('"
93 -- Parse the expressions
94 for k,v in pairs(expr) do
96 v = v:gsub("%%", "%%%%")
99 re = r_include:format(sanitize(string.sub(v, 2)))
102 re = sanitize(v):gsub(":(.-) (.*)", r_i18n)
104 re = sanitize(v):gsub(":(.+)", r_i18n2)
107 re = r_pexec:format(v:sub(2))
111 re = r_exec:format(v)
113 template = template:gsub("<%%"..tostring(k).."%%>", re)
116 return loadstring(template)
119 -- Oldstyle render shortcut
120 function render(name, scope, ...)
121 scope = scope or getfenv(2)
122 local s, t = luci.util.copcall(Template, name)
132 Template = luci.util.class()
134 -- Shared template cache to store templates in to avoid unnecessary reloading
136 setmetatable(Template.cache, {__mode = "v"})
139 -- Constructor - Reads and compiles the template on-demand
140 function Template.__init__(self, name)
141 self.template = self.cache[name]
143 -- Create a new namespace for this template
146 -- Copy over from general namespace
147 luci.util.update(self.viewns, viewns)
148 if context.viewns then
149 luci.util.update(self.viewns, context.viewns)
152 -- If we have a cached template, skip compiling and loading
153 if self.template then
157 -- Enforce cache security
158 local cdir = compiledir .. "/" .. luci.sys.process.info("uid")
161 local sourcefile = viewdir .. "/" .. name .. ".htm"
162 local compiledfile = cdir .. "/" .. luci.http.urlencode(name) .. ".lua"
165 if compiler_mode == "file" then
166 local tplmt = luci.fs.mtime(sourcefile)
167 local commt = luci.fs.mtime(compiledfile)
169 if not luci.fs.mtime(cdir) then
170 luci.fs.mkdir(cdir, true)
171 luci.fs.chmod(luci.fs.dirname(cdir), "a+rxw")
174 -- Build if there is no compiled file or if compiled file is outdated
175 if ((commt == nil) and not (tplmt == nil))
176 or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
178 source, err = luci.fs.readfile(sourcefile)
181 local compiled, err = compile(source)
183 luci.fs.writefile(compiledfile, luci.util.get_bytecode(compiled))
184 self.template = compiled
187 self.template, err = loadfile(compiledfile)
190 elseif compiler_mode == "none" then
191 self.template, err = loadfile(self.compiledfile)
193 elseif compiler_mode == "memory" then
195 source, err = luci.fs.readfile(sourcefile)
197 self.template, err = compile(source)
202 -- If we have no valid template throw error, otherwise cache the template
203 if not self.template then
206 self.cache[name] = self.template
211 -- Renders a template
212 function Template.render(self, scope)
213 scope = scope or getfenv(2)
215 -- Save old environment
216 local oldfenv = getfenv(self.template)
218 -- Put our predefined objects in the scope of the template
219 luci.util.resfenv(self.template)
220 luci.util.updfenv(self.template, scope)
221 luci.util.updfenv(self.template, self.viewns)
223 -- Now finally render the thing
227 setfenv(self.template, oldfenv)