Merge branch 'menu'
[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.dispatcher(),
56         uploadctrl = ffluci.http.dispatcher_upload(),
57         media      = ffluci.config.main.mediaurlbase,
58         resource   = ffluci.config.main.resourcebase,
59         write      = io.write,
60         include    = function(name) Template(name):render(getfenv(2)) end,      
61 }
62
63 -- Compiles a given template into an executable Lua module
64 function compile(template)      
65         -- Search all <% %> expressions (remember: Lua table indexes begin with #1)
66         local function expr_add(command)
67                 table.insert(expr, command)
68                 return "<%" .. tostring(#expr) .. "%>"
69         end
70         
71         -- As "expr" should be local, we have to assign it to the "expr_add" scope 
72         local expr = {}
73         ffluci.util.extfenv(expr_add, "expr", expr)
74         
75         -- Save all expressiosn to table "expr"
76         template = template:gsub("<%%(.-)%%>", expr_add)
77         
78         local function sanitize(s)
79                 s = ffluci.util.escape(s)
80                 s = ffluci.util.escape(s, "'")
81                 s = ffluci.util.escape(s, "\n")
82                 return s
83         end
84         
85         -- Escape and sanitize all the template (all non-expressions)
86         template = sanitize(template)
87
88         -- Template module header/footer declaration
89         local header = "write('"
90         local footer = "')"
91         
92         template = header .. template .. footer
93         
94         -- Replacements
95         local r_include = "')\ninclude('%s')\nwrite('"
96         local r_i18n    = "'..translate('%1','%2')..'"
97         local r_uci     = "'..config('%1','%2','%3')..'"
98         local r_pexec   = "'..(%s or '')..'"
99         local r_exec    = "')\n%s\nwrite('"
100         
101         -- Parse the expressions
102         for k,v in pairs(expr) do
103                 local p = v:sub(1, 1)
104                 local re = nil
105                 if p == "+" then
106                         re = r_include:format(sanitize(string.sub(v, 2)))
107                 elseif p == ":" then
108                         re = sanitize(v):gsub(":(.-) (.+)", r_i18n)
109                 elseif p == "~" then
110                         re = sanitize(v):gsub("~(.-)%.(.-)%.(.+)", r_uci)
111                 elseif p == "=" then
112                         re = r_pexec:format(v:sub(2))
113                 else
114                         re = r_exec:format(v)
115                 end
116                 template = template:gsub("<%%"..tostring(k).."%%>", re)
117         end
118
119         if compiler_enable_bytecode then 
120                 tf = loadstring(template)
121                 template = string.dump(tf)
122         end
123         
124         return template
125 end
126
127 -- Oldstyle render shortcut
128 function render(name, scope, ...)
129         scope = scope or getfenv(2)
130         local s, t = pcall(Template, name)
131         if not s then
132                 error(t)
133         else
134                 t:render(scope, ...)
135         end
136 end
137
138
139 -- Template class
140 Template = ffluci.util.class()
141
142 -- Shared template cache to store templates in to avoid unnecessary reloading
143 Template.cache = {}
144
145
146 -- Constructor - Reads and compiles the template on-demand
147 function Template.__init__(self, name)  
148         if self.cache[name] then
149                 self.template = self.cache[name]
150         else
151                 self.template = nil
152         end
153         
154         -- Create a new namespace for this template
155         self.viewns = {}
156         
157         -- Copy over from general namespace
158         for k, v in pairs(viewns) do
159                 self.viewns[k] = v
160         end     
161         
162         -- If we have a cached template, skip compiling and loading
163         if self.template then
164                 return
165         end
166         
167         -- Compile and build
168         local sourcefile   = viewdir .. name .. ".htm"
169         local compiledfile = viewdir .. name .. ".lua"
170         local err       
171         
172         if compiler_mode == "file" then
173                 local tplmt = ffluci.fs.mtime(sourcefile)
174                 local commt = ffluci.fs.mtime(compiledfile)
175                                 
176                 -- Build if there is no compiled file or if compiled file is outdated
177                 if ((commt == nil) and not (tplmt == nil))
178                 or (not (commt == nil) and not (tplmt == nil) and commt < tplmt) then
179                         local source
180                         source, err = ffluci.fs.readfile(sourcefile)
181                         
182                         if source then
183                                 local compiled = compile(source)
184                                 ffluci.fs.writefile(compiledfile, compiled)
185                                 self.template, err = loadstring(compiled)
186                         end
187                 else
188                         self.template, err = loadfile(compiledfile)
189                 end
190                 
191         elseif compiler_mode == "none" then
192                 self.template, err = loadfile(self.compiledfile)
193                 
194         elseif compiler_mode == "memory" then
195                 local source
196                 source, err = ffluci.fs.readfile(sourcefile)
197                 if source then
198                         self.template, err = loadstring(compile(source))
199                 end
200                         
201         end
202         
203         -- If we have no valid template throw error, otherwise cache the template
204         if not self.template then
205                 error(err)
206         else
207                 self.cache[name] = self.template
208         end
209 end
210
211
212 -- Renders a template
213 function Template.render(self, scope)
214         scope = scope or getfenv(2)
215         
216         -- Save old environment
217         local oldfenv = getfenv(self.template)
218         
219         -- Put our predefined objects in the scope of the template
220         ffluci.util.resfenv(self.template)
221         ffluci.util.updfenv(self.template, scope)
222         ffluci.util.updfenv(self.template, self.viewns)
223         
224         -- Now finally render the thing
225         self.template()
226         
227         -- Reset environment
228         setfenv(self.template, oldfenv)
229 end