* CBI: Minor changes
[project/luci.git] / core / src / template.lua
1 --[[
2 FFLuCI - 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("ffluci.template", package.seeall)
27
28 require("ffluci.config")
29 require("ffluci.util")
30 require("ffluci.fs")
31 require("ffluci.http")
32
33 viewdir = ffluci.sys.libpath() .. "/view/"
34
35
36 -- Compile modes:
37 -- none: Never compile, only use precompiled data from files
38 -- memory: Always compile, do not save compiled files, ignore precompiled
39 -- file: Compile on demand, save compiled files, update precompiled
40 compiler_mode = "memory"
41
42
43 -- This applies to compiler modes "always" and "smart"
44 --
45 -- Produce compiled lua code rather than lua sourcecode
46 -- WARNING: Increases template size heavily!!!
47 -- This produces the same bytecode as luac but does not have a strip option
48 compiler_enable_bytecode = false
49
50
51 -- Define the namespace for template modules
52 viewns = {
53 translate = function(...) return require("ffluci.i18n").translate(...) end,
54 config = function(...) return require("ffluci.model.uci").get(...) or "" end,
55 controller = ffluci.http.env.SCRIPT_NAME or "",
56 media = ffluci.config.main.mediaurlbase,
57 write = io.write,
58 include = function(name) Template(name):render(getfenv(2)) end,
59 }
60
61 -- Compiles a given template into an executable Lua module
62 function compile(template)
63 -- Search all <% %> expressions (remember: Lua table indexes begin with #1)
64 local function expr_add(command)
65 table.insert(expr, command)
66 return "<%" .. tostring(#expr) .. "%>"
67 end
68
69 -- As "expr" should be local, we have to assign it to the "expr_add" scope
70 local expr = {}
71 ffluci.util.extfenv(expr_add, "expr", expr)
72
73 -- Save all expressiosn to table "expr"
74 template = template:gsub("<%%(.-)%%>", expr_add)
75
76 local function sanitize(s)
77 s = ffluci.util.escape(s)
78 s = ffluci.util.escape(s, "'")
79 s = ffluci.util.escape(s, "\n")
80 return s
81 end
82
83 -- Escape and sanitize all the template (all non-expressions)
84 template = sanitize(template)
85
86 -- Template module header/footer declaration
87 local header = "write('"
88 local footer = "')"
89
90 template = header .. template .. footer
91
92 -- Replacements
93 local r_include = "')\ninclude('%s')\nwrite('"
94 local r_i18n = "'..translate('%1','%2')..'"
95 local r_uci = "'..config('%1','%2','%3')..'"
96 local r_pexec = "'..(%s or '')..'"
97 local r_exec = "')\n%s\nwrite('"
98
99 -- Parse the expressions
100 for k,v in pairs(expr) do
101 local p = v:sub(1, 1)
102 local re = nil
103 if p == "+" then
104 re = r_include:format(sanitize(string.sub(v, 2)))
105 elseif p == ":" then
106 re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
107 elseif p == "~" then
108 re = sanitize(v):gsub("~(.-)%.(.-)%.(.+)", r_uci)
109 elseif p == "=" then
110 re = r_pexec:format(v:sub(2))
111 else
112 re = r_exec:format(v)
113 end
114 template = template:gsub("<%%"..tostring(k).."%%>", re)
115 end
116
117 if compiler_enable_bytecode then
118 tf = loadstring(template)
119 template = string.dump(tf)
120 end
121
122 return template
123 end
124
125 -- Oldstyle render shortcut
126 function render(name, scope, ...)
127 scope = scope or getfenv(2)
128 local s, t = pcall(Template, name)
129 if not s then
130 error(t)
131 else
132 t:render(scope, ...)
133 end
134 end
135
136
137 -- Template class
138 Template = ffluci.util.class()
139
140 -- Shared template cache to store templates in to avoid unnecessary reloading
141 Template.cache = {}
142
143
144 -- Constructor - Reads and compiles the template on-demand
145 function Template.__init__(self, name)
146 if self.cache[name] then
147 self.template = self.cache[name]
148 else
149 self.template = nil
150 end
151
152 -- Create a new namespace for this template
153 self.viewns = {}
154
155 -- Copy over from general namespace
156 for k, v in pairs(viewns) do
157 self.viewns[k] = v
158 end
159
160 -- If we have a cached template, skip compiling and loading
161 if self.template then
162 return
163 end
164
165 -- Compile and build
166 local sourcefile = viewdir .. name .. ".htm"
167 local compiledfile = viewdir .. name .. ".lua"
168 local err
169
170 if compiler_mode == "file" then
171 local tplmt = ffluci.fs.mtime(sourcefile)
172 local commt = ffluci.fs.mtime(compiledfile)
173
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
177 local source
178 source, err = ffluci.fs.readfile(sourcefile)
179
180 if source then
181 local compiled = compile(source)
182 ffluci.fs.writefile(compiledfile, compiled)
183 self.template, err = loadstring(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 = ffluci.fs.readfile(sourcefile)
195 if source then
196 self.template, err = loadstring(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 ffluci.util.resfenv(self.template)
219 ffluci.util.updfenv(self.template, scope)
220 ffluci.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