Module:I18n: Difference between revisions
From Elwiki
(Add i18n.getTranslatedTitle) |
mNo edit summary |
||
Line 66: | Line 66: | ||
local tp = mw.title.makeTitle('', title_full) | local tp = mw.title.makeTitle('', title_full) | ||
if tp.exists then | if tp.exists then | ||
display_title = string.match(tp:getContent(), "%{%{DISPLAYTITLE:([^}] | display_title = string.match(tp:getContent(), "%{%{DISPLAYTITLE:([^}]+)%}%}") | ||
end | end | ||
end | end |
Latest revision as of 12:05, 12 March 2024
Documentation for this module may be created at Module:I18n/doc
-- This module provides easy processing of i18n in Scribunto.
-- It is intended for use by other Lua modules, and should not be
-- called from #invoke directly.
require('Module:CommonFunctions')
local libraryUtil = require('libraryUtil')
local checkType = libraryUtil.checkType
local i18n = {}
function i18n.getTranslations(frame, title, lang, trimValues)
checkType('getTranslations', 1, frame, 'table', true)
checkType('getTranslations', 2, title, 'string', true)
checkType('getTranslations', 3, lang, 'string', true)
checkType('getTranslations', 4, trimValues, 'boolean', true)
frame = frame or {}
title = title or ""
lang = lang or ""
local translations = {}
--[[
If title or lang missing, this means no translation given.
In such case, return empty translation map, and the search step
will fail to search key.
--]]
if not title or not lang then
return translations
end
local lang_suffix = lang and ('/' .. lang) or ''
--[[
Try to get translation array from page
--]]
local tp = title .. lang_suffix
local translate_lines = split(
frame:preprocess('{{#ifexist:' .. tp .. '|{{:' .. tp .. '}}{{#arrayprint:$t}}|}}') or '')
for _, translate_line in ipairs(translate_lines) do
-- Key should always without spaces, so apply trim to it directly.
local equal_start, equal_end = string.find(translate_line, '=')
if equal_start then
local key = trim(string.sub(translate_line, 1, equal_start - 1))
local value = string.sub(translate_line, equal_end + 1)
if trimValues ~= false then
value = trim(value)
end
if key then
translations[key] = value
end
end
end
return translations
end
function i18n.getTranslatedTitle(title, lang)
title = title or ''
lang = lang or ''
local title_full = title .. lang
local display_title
if title_full then
local tp = mw.title.makeTitle('', title_full)
if tp.exists then
display_title = string.match(tp:getContent(), "%{%{DISPLAYTITLE:([^}]+)%}%}")
end
end
return display_title
end
function i18n.translate(translations, key)
translations = translations or {}
return (translations[key] or key or '')
end
return i18n