diff options
author | Jo-Philipp Wich <jow@openwrt.org> | 2014-09-04 11:35:15 +0000 |
---|---|---|
committer | Jo-Philipp Wich <jow@openwrt.org> | 2014-09-04 11:35:15 +0000 |
commit | 8fab048554b38760584b1aa348516e6d44b804c1 (patch) | |
tree | 4cfc71b0754137355d90efe88affa76e01408860 /modules/base | |
parent | 35eaa9f85f89be1fe0edf4dd3036d14f4848eed4 (diff) |
libs/web: add support for string templates to luci.template module
Signed-off-by: Matthias Schiffer <mschiffer@universe-factory.net>
Diffstat (limited to 'modules/base')
-rw-r--r-- | modules/base/luasrc/template.lua | 30 |
1 files changed, 23 insertions, 7 deletions
diff --git a/modules/base/luasrc/template.lua b/modules/base/luasrc/template.lua index 72127d1df..ea01d3c21 100644 --- a/modules/base/luasrc/template.lua +++ b/modules/base/luasrc/template.lua @@ -50,6 +50,13 @@ function render(name, scope) return Template(name):render(scope or getfenv(2)) end +--- Render a template from a string. +-- @param template Template string +-- @param scope Scope to assign to template (optional) +function render_string(template, scope) + return Template(nil, template):render(scope or getfenv(2)) +end + -- Template class Template = util.class() @@ -59,11 +66,14 @@ Template.cache = setmetatable({}, {__mode = "v"}) -- Constructor - Reads and compiles the template on-demand -function Template.__init__(self, name) +function Template.__init__(self, name, template) + if name then + self.template = self.cache[name] + self.name = name + else + self.name = "[string]" + end - self.template = self.cache[name] - self.name = name - -- Create a new namespace for this template self.viewns = context.viewns @@ -72,16 +82,22 @@ function Template.__init__(self, name) -- Compile template local err - local sourcefile = viewdir .. "/" .. name .. ".htm" + local sourcefile - self.template, _, err = tparser.parse(sourcefile) + if name then + sourcefile = viewdir .. "/" .. name .. ".htm" + self.template, _, err = tparser.parse(sourcefile) + else + sourcefile = "[string]" + self.template, _, err = tparser.parse_string(template) + end -- If we have no valid template throw error, otherwise cache the template if not self.template then error("Failed to load template '" .. name .. "'.\n" .. "Error while parsing template '" .. sourcefile .. "':\n" .. (err or "Unknown syntax error")) - else + elseif name then self.cache[name] = self.template end end |