Module:I18n

From Elwiki
Revision as of 19:23, 11 March 2024 by Boxsnake (talk | contribs) (Fix non-existent translations)

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.translate(translations, key)
    translations = translations or {}
    return (translations[key] or key or '')
end

return i18n