luci-base: expose system translations to JavaScript
authorJo-Philipp Wich <jo@mein.io>
Thu, 18 Oct 2018 11:44:39 +0000 (13:44 +0200)
committerJo-Philipp Wich <jo@mein.io>
Mon, 5 Nov 2018 10:01:45 +0000 (11:01 +0100)
Add a new /admin/translations/ endpoint which exposes the loaded system
translations as JavaScript file.

Once referenced by <script>, the endpoint will create a `window.TR` object
containing the entire translation string table for use on the client side.

Signed-off-by: Jo-Philipp Wich <jo@mein.io>
modules/luci-base/luasrc/controller/admin/index.lua

index 9a084d10e27f5e63b50d102b4590f81593ad8d9a..39004c6760222310833c66642e85b7095b79dba4 100644 (file)
@@ -82,6 +82,9 @@ function index()
                page.leaf = true
        end
 
+       page = entry({"admin", "translations"}, call("action_translations"), nil)
+       page.leaf = true
+
        -- Logout is last
        entry({"admin", "logout"}, call("action_logout"), _("Logout"), 999)
 end
@@ -102,6 +105,27 @@ function action_logout()
        luci.http.redirect(dsp.build_url())
 end
 
+function action_translations(lang)
+       local i18n = require "luci.i18n"
+       local http = require "luci.http"
+       local fs = require "nixio".fs
+
+       if lang and #lang > 0 then
+               lang = i18n.setlanguage(lang)
+               if lang then
+                       local s = fs.stat("%s/base.%s.lmo" %{ i18n.i18ndir, lang })
+                       if s then
+                               http.header("Cache-Control", "public, max-age=31536000")
+                               http.header("ETag", "%x-%x-%x" %{ s["ino"], s["size"], s["mtime"] })
+                       end
+               end
+       end
+
+       http.prepare_content("application/javascript; charset=utf-8")
+       http.write("window.TR=")
+       http.write_json(i18n.dump())
+end
+
 
 function lease_status()
        local s = require "luci.tools.status"