template.lua 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. -- Copyright 2008 Steven Barth <steven@midlink.org>
  2. -- Copyright 2017 Matthias Schiffer <mschiffer@universe-factory.net>
  3. -- Licensed to the public under the Apache License 2.0.
  4. local tparser = require "gluon.web.template.parser"
  5. local util = require "gluon.web.util"
  6. local fs = require "nixio.fs"
  7. local tostring, setmetatable, setfenv, pcall, assert = tostring, setmetatable, setfenv, pcall, assert
  8. module "gluon.web.template"
  9. local viewdir = util.libpath() .. "/view/"
  10. local i18ndir = util.libpath() .. "/i18n/"
  11. function renderer(env)
  12. local ctx = {}
  13. local function render_template(name, template, scope)
  14. scope = scope or {}
  15. local locals = {
  16. renderer = ctx,
  17. translate = ctx.translate,
  18. translatef = ctx.translatef,
  19. include = function(name)
  20. ctx.render(name, scope)
  21. end,
  22. }
  23. setfenv(template, setmetatable({}, {
  24. __index = function(tbl, key)
  25. return scope[key] or env[key] or locals[key]
  26. end
  27. }))
  28. -- Now finally render the thing
  29. local stat, err = pcall(template)
  30. assert(stat, "Failed to execute template '" .. name .. "'.\n" ..
  31. "A runtime error occured: " .. tostring(err or "(nil)"))
  32. end
  33. --- Render a certain template.
  34. -- @param name Template name
  35. -- @param scope Scope to assign to template (optional)
  36. function ctx.render(name, scope)
  37. local sourcefile = viewdir .. name .. ".html"
  38. local template, _, err = tparser.parse(sourcefile)
  39. assert(template, "Failed to load template '" .. name .. "'.\n" ..
  40. "Error while parsing template '" .. sourcefile .. "':\n" ..
  41. (err or "Unknown syntax error"))
  42. render_template(name, template, scope)
  43. end
  44. --- Render a template from a string.
  45. -- @param template Template string
  46. -- @param scope Scope to assign to template (optional)
  47. function ctx.render_string(str, scope)
  48. local template, _, err = tparser.parse_string(str)
  49. assert(template, "Error while parsing template:\n" ..
  50. (err or "Unknown syntax error"))
  51. render_template('(local)', template, scope)
  52. end
  53. function ctx.setlanguage(lang)
  54. lang = lang:gsub("_", "-")
  55. if not lang then return false end
  56. if lang ~= 'en' and not fs.access(i18ndir .. "gluon-web." .. lang .. ".lmo") then
  57. return false
  58. end
  59. return tparser.load_catalog(lang, i18ndir)
  60. end
  61. function ctx.translate(key)
  62. return tparser.translate(key) or key
  63. end
  64. function ctx.translatef(key, ...)
  65. local t = ctx.translate(key)
  66. return t and t:format(...)
  67. end
  68. return ctx
  69. end