From 9939fc5a26d07da4756497bb6a7dc51dcf379e98 Mon Sep 17 00:00:00 2001 From: Jo-Philipp Wich Date: Thu, 23 Jan 2020 21:53:26 +0100 Subject: luci-base: add support for plural translations and contexts in Lua api - Introduce a new luci.template.parser.ntranslate() function which takes a count, a singular and a plural translation string as well as an optional context argument and returns the appropriate, language specific plural translation. - Introduce an optional translation context argument in the existing luci.template.parser.translate() function - Support translation contexts in LuCI template directives. Translation messages are split on the first unescaped pipe character and the reamining string after the pipe is treated as context. Examples: - `string.format(p.ntranslate(n, "1 apple", "%d apples"), n)` will return an appropriate plural translation for the given amount. - `translate("Load", "The system load")` will return an appropiate translation for `Load`, using `The system load` as disambiguation context (a `msgctxt` directive in *.po files). - Likewise `<%:Load|The system load%>` will translate the word `Load` while using the remainder of the string as context. - To use pipes in translations strings literally, they must be escaped: `<%:Use the "\|" character%>` will translate the literal string `Use the "|" character`. Signed-off-by: Jo-Philipp Wich --- modules/luci-base/src/template_utils.c | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) (limited to 'modules/luci-base/src/template_utils.c') diff --git a/modules/luci-base/src/template_utils.c b/modules/luci-base/src/template_utils.c index 0411932ce9..8580405e32 100644 --- a/modules/luci-base/src/template_utils.c +++ b/modules/luci-base/src/template_utils.c @@ -474,10 +474,26 @@ void luastr_escape(struct template_buffer *out, const char *s, unsigned int l, void luastr_translate(struct template_buffer *out, const char *s, unsigned int l, int escape_xml) { + int trlen, idlen = l, ctxtlen = 0, esc = 0; + const char *p, *msgid = s, *msgctxt = NULL; char *tr; - int trlen; - if (!lmo_translate(s, l, &tr, &trlen)) + for (p = s; p < s + l; p++) { + if (esc) { + esc = 0; + } + else if (*p == '\\') { + esc = 1; + } + else if (*p == '|') { + idlen = p - s; + msgctxt = p + 1; + ctxtlen = s + l - msgctxt; + break; + } + } + + if (!lmo_translate_ctxt(msgid, idlen, msgctxt, ctxtlen, &tr, &trlen)) luastr_escape(out, tr, trlen, escape_xml); else luastr_escape(out, s, l, escape_xml); -- cgit v1.2.3