0004-libs-web-add-support-for-string-templates-to-luci.template-module.patch 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. From: Matthias Schiffer <mschiffer@universe-factory.net>
  2. Date: Fri, 16 May 2014 11:48:42 +0200
  3. Subject: libs/web: add support for string templates to luci.template module
  4. diff --git a/libs/web/luasrc/template.lua b/libs/web/luasrc/template.lua
  5. index 72127d1..ea01d3c 100644
  6. --- a/libs/web/luasrc/template.lua
  7. +++ b/libs/web/luasrc/template.lua
  8. @@ -50,6 +50,13 @@ function render(name, scope)
  9. return Template(name):render(scope or getfenv(2))
  10. end
  11. +--- Render a template from a string.
  12. +-- @param template Template string
  13. +-- @param scope Scope to assign to template (optional)
  14. +function render_string(template, scope)
  15. + return Template(nil, template):render(scope or getfenv(2))
  16. +end
  17. +
  18. -- Template class
  19. Template = util.class()
  20. @@ -59,11 +66,14 @@ Template.cache = setmetatable({}, {__mode = "v"})
  21. -- Constructor - Reads and compiles the template on-demand
  22. -function Template.__init__(self, name)
  23. +function Template.__init__(self, name, template)
  24. + if name then
  25. + self.template = self.cache[name]
  26. + self.name = name
  27. + else
  28. + self.name = "[string]"
  29. + end
  30. - self.template = self.cache[name]
  31. - self.name = name
  32. -
  33. -- Create a new namespace for this template
  34. self.viewns = context.viewns
  35. @@ -72,16 +82,22 @@ function Template.__init__(self, name)
  36. -- Compile template
  37. local err
  38. - local sourcefile = viewdir .. "/" .. name .. ".htm"
  39. + local sourcefile
  40. - self.template, _, err = tparser.parse(sourcefile)
  41. + if name then
  42. + sourcefile = viewdir .. "/" .. name .. ".htm"
  43. + self.template, _, err = tparser.parse(sourcefile)
  44. + else
  45. + sourcefile = "[string]"
  46. + self.template, _, err = tparser.parse_string(template)
  47. + end
  48. -- If we have no valid template throw error, otherwise cache the template
  49. if not self.template then
  50. error("Failed to load template '" .. name .. "'.\n" ..
  51. "Error while parsing template '" .. sourcefile .. "':\n" ..
  52. (err or "Unknown syntax error"))
  53. - else
  54. + elseif name then
  55. self.cache[name] = self.template
  56. end
  57. end