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 "nixio.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 nixio = require "nixio", require "nixio.util"
34 local tparser = require "luci.template.parser"
36 local tostring, pairs, loadstring = tostring, pairs, loadstring
37 local setmetatable, loadfile = setmetatable, loadfile
38 local getfenv, setfenv, rawget = getfenv, setfenv, rawget
39 local assert, type, error = assert, type, error
41 --- LuCI template library.
42 module "luci.template"
44 config.template = config.template or {}
45 viewdir = config.template.viewdir or util.libpath() .. "/view"
48 -- Define the namespace for template modules
49 context = util.threadlocal()
51 --- Render a certain template.
52 -- @param name Template name
53 -- @param scope Scope to assign to template (optional)
54 function render(name, scope)
55 return Template(name):render(scope or getfenv(2))
60 Template = util.class()
62 -- Shared template cache to store templates in to avoid unnecessary reloading
63 Template.cache = setmetatable({}, {__mode = "v"})
66 -- Constructor - Reads and compiles the template on-demand
67 function Template.__init__(self, name)
69 self.template = self.cache[name]
72 -- Create a new namespace for this template
73 self.viewns = context.viewns
75 -- If we have a cached template, skip compiling and loading
76 if not self.template then
79 local sourcefile = viewdir .. "/" .. name .. ".htm"
80 self.template, _, err = tparser.parse(sourcefile)
82 -- If we have no valid template throw error, otherwise cache the template
83 if not self.template then
86 self.cache[name] = self.template
93 function Template.render(self, scope)
94 scope = scope or getfenv(2)
96 -- Put our predefined objects in the scope of the template
97 setfenv(self.template, setmetatable({}, {__index =
99 return rawget(tbl, key) or self.viewns[key] or scope[key]
102 -- Now finally render the thing
103 local stat, err = util.copcall(self.template)
105 error("Error in template %s: %s" % {self.name, err})