i18n.lua 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. -- Copyright 2018 Matthias Schiffer <mschiffer@universe-factory.net>
  2. -- Licensed to the public under the Apache License 2.0.
  3. local tparser = require "gluon.web.template.parser"
  4. local util = require "gluon.web.util"
  5. local fs = require "nixio.fs"
  6. local i18ndir = util.libpath() .. "/i18n"
  7. local function i18n_file(lang, pkg)
  8. return string.format('%s/%s.%s.lmo', i18ndir, pkg, lang)
  9. end
  10. local function no_translation(key)
  11. return nil
  12. end
  13. local function load_catalog(lang, pkg)
  14. if pkg then
  15. local file = i18n_file(lang, pkg)
  16. local cat = fs.access(file) and tparser.load_catalog(file)
  17. if cat then return cat end
  18. end
  19. return no_translation
  20. end
  21. module "gluon.web.i18n"
  22. function supported(lang)
  23. return lang == 'en' or fs.access(i18n_file(lang, 'gluon-web'))
  24. end
  25. function load(lang, pkg)
  26. local _translate = load_catalog(lang, pkg)
  27. local function translate(key)
  28. return _translate(key) or key
  29. end
  30. local function translatef(key, ...)
  31. return translate(key):format(...)
  32. end
  33. return {
  34. _translate = _translate,
  35. translate = translate,
  36. translatef = translatef,
  37. }
  38. end