* luci/libs/web: extended template syntax to allow removal of leading and trailing...
[project/luci.git] / libs / web / luasrc / template.lua
1 --[[
2 LuCI - Template Parser
3
4 Description:
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.
7
8 FileId: $Id$
9
10 License:
11 Copyright 2008 Steven Barth <steven@midlink.org>
12
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
16
17 http://www.apache.org/licenses/LICENSE-2.0
18
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.
24
25 ]]--
26 module("luci.template", package.seeall)
27
28 require("luci.config")
29 require("luci.util")
30 require("luci.fs")
31 require("luci.http")
32
33 luci.config.template = luci.config.template or {}
34
35 viewdir = luci.config.template.viewdir or luci.sys.libpath() .. "/view"
36 compiledir = luci.config.template.compiledir or luci.sys.libpath() .. "/view"
37
38
39 -- Compile modes:
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"
44
45
46 -- Define the namespace for template modules
47 context = luci.util.threadlocal()
48
49 viewns = {
50 include = function(name) Template(name):render(getfenv(2)) end,
51 }
52
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 and "" or ws1 ) ..
59 "<%" .. tostring(#expr) .. "%>" ..
60 ( skip2 and "" or ws2 )
61 end
62
63 -- As "expr" should be local, we have to assign it to the "expr_add" scope
64 local expr = {}
65 luci.util.extfenv(expr_add, "expr", expr)
66
67 -- Save all expressiosn to table "expr"
68 template = template:gsub("(%s*)<%%(%-?)(.-)(%-?)%%>(%s*)", expr_add)
69
70 local function sanitize(s)
71 s = luci.util.escape(s)
72 s = luci.util.escape(s, "'")
73 s = luci.util.escape(s, "\n")
74 return s
75 end
76
77 -- Escape and sanitize all the template (all non-expressions)
78 template = sanitize(template)
79
80 -- Template module header/footer declaration
81 local header = "write('"
82 local footer = "')"
83
84 template = header .. template .. footer
85
86 -- Replacements
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('"
92
93 -- Parse the expressions
94 for k,v in pairs(expr) do
95 local p = v:sub(1, 1)
96 local re = nil
97 if p == "+" then
98 re = r_include:format(sanitize(string.sub(v, 2)))
99 elseif p == ":" then
100 if v:find(" ") then
101 re = sanitize(v):gsub(":(.-) (.*)", r_i18n)
102 else
103 re = sanitize(v):gsub(":(.+)", r_i18n2)
104 end
105 elseif p == "=" then
106 re = r_pexec:format(v:sub(2))
107 elseif p == "#" then
108 re = ""
109 else
110 re = r_exec:format(v)
111 end
112 template = template:gsub("<%%"..tostring(k).."%%>", re)
113 end
114
115 return loadstring(template)
116 end
117
118 -- Oldstyle render shortcut
119 function render(name, scope, ...)
120 scope = scope or getfenv(2)
121 local s, t = luci.util.copcall(Template, name)
122 if not s then
123 error(t)
124 else
125 t:render(scope, ...)
126 end
127 end
128
129
130 -- Template class
131 Template = luci.util.class()
132
133 -- Shared template cache to store templates in to avoid unnecessary reloading
134 Template.cache = {}
135 setmetatable(Template.cache, {__mode = "v"})
136
137
138 -- Constructor - Reads and compiles the template on-demand
139 function Template.__init__(self, name)
140 self.template = self.cache[name]
141
142 -- Create a new namespace for this template
143 self.viewns = {}
144
145 -- Copy over from general namespace
146 luci.util.update(self.viewns, viewns)
147 if context.viewns then
148 luci.util.update(self.viewns, context.viewns)
149 end
150
151 -- If we have a cached template, skip compiling and loading
152 if self.template then
153 return
154 end
155
156 -- Enforce cache security
157 local cdir = compiledir .. "/" .. luci.sys.process.info("uid")
158
159 -- Compile and build
160 local sourcefile = viewdir .. "/" .. name .. ".htm"
161 local compiledfile = cdir .. "/" .. luci.http.urlencode(name) .. ".lua"
162 local err
163
164 if compiler_mode == "file" then
165 local tplmt = luci.fs.mtime(sourcefile)
166 local commt = luci.fs.mtime(compiledfile)
167
168 if not luci.fs.mtime(cdir) then
169 luci.fs.mkdir(cdir, true)
170 luci.fs.chmod(luci.fs.dirname(cdir), "a+rxw")
171 end
172
173 -- Build if there is no compiled file or if compiled file is outdated
174 if ((commt == nil) and not (tplmt == nil))
175 or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
176 local source
177 source, err = luci.fs.readfile(sourcefile)
178
179 if source then
180 local compiled, err = compile(source)
181
182 luci.fs.writefile(compiledfile, luci.util.dump(compiled))
183 self.template = compiled
184 end
185 else
186 self.template, err = loadfile(compiledfile)
187 end
188
189 elseif compiler_mode == "none" then
190 self.template, err = loadfile(self.compiledfile)
191
192 elseif compiler_mode == "memory" then
193 local source
194 source, err = luci.fs.readfile(sourcefile)
195 if source then
196 self.template, err = compile(source)
197 end
198
199 end
200
201 -- If we have no valid template throw error, otherwise cache the template
202 if not self.template then
203 error(err)
204 else
205 self.cache[name] = self.template
206 end
207 end
208
209
210 -- Renders a template
211 function Template.render(self, scope)
212 scope = scope or getfenv(2)
213
214 -- Save old environment
215 local oldfenv = getfenv(self.template)
216
217 -- Put our predefined objects in the scope of the template
218 luci.util.resfenv(self.template)
219 luci.util.updfenv(self.template, scope)
220 luci.util.updfenv(self.template, self.viewns)
221
222 -- Now finally render the thing
223 self.template()
224
225 -- Reset environment
226 setfenv(self.template, oldfenv)
227 end