Module:UnitLinker

From Heroes of Might and Magic: Olden Era Official Wiki
Revision as of 15:31, 13 June 2026 by akesha.taladim (talk | contribs) (Created page with "local p = {} -- Fonction pour déterminer la langue à partir du titre de la page local function getLanguage() local title = mw.title.getCurrentTitle().text local lang = mw.ustring.match(title, "/([a-z_]+)$") if not lang or lang == "en" then return "en" end return lang end -- Fonction pour vérifier si un nom d'unité est valide et obtenir son nom anglais de base local function resolveUnit(name) -- Recherche dans la table Translation pour trouver le...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation for this module may be created at Module:UnitLinker/doc

local p = {}

-- Fonction pour déterminer la langue à partir du titre de la page
local function getLanguage()
    local title = mw.title.getCurrentTitle().text
    local lang = mw.ustring.match(title, "/([a-z_]+)$")
    if not lang or lang == "en" then return "en" end
    return lang
end

-- Fonction pour vérifier si un nom d'unité est valide et obtenir son nom anglais de base
local function resolveUnit(name)
    -- Recherche dans la table Translation pour trouver le nom anglais (target_id)
    -- si le nom fourni est déjà une traduction
    local res = mw.ext.cargo.query("Translation", "target_id", {
        where = "type = 'unit' AND name = '" .. name .. "'",
        limit = 1
    })
    
    if res and #res > 0 then return res[1].target_id end
    
    -- Sinon, vérifier si le nom est déjà un nom anglais valide dans la table Unit
    local unitCheck = mw.ext.cargo.query("Unit", "id", { where = "id = '" .. name .. "'", limit = 1 })
    if unitCheck and #unitCheck > 0 then return name end
    
    return nil
end

-- Fonction principale appelée par {{#invoke:UnitLinker|link|Ton texte ici}}
function p.link(frame)
    local text = frame.args[1] or ""
    local lang = getLanguage()
    
    -- On utilise une fonction de remplacement globale
    local processedText = mw.ustring.gsub(text, "([%a%s]+)", function(match)
        local unitName = mw.text.trim(match)
        local baseName = resolveUnit(unitName)
        
        if baseName then
            -- Si anglais, lien simple
            if lang == "en" then
                return "[[" .. baseName .. "]]"
            else
                -- Si autre langue, on cherche le nom traduit pour le display
                local trans = mw.ext.cargo.query("Translation", "name", {
                    where = "type = 'unit' AND target_id = '" .. baseName .. "' AND language = '" .. lang .. "'",
                    limit = 1
                })
                local displayName = (trans and #trans > 0) and trans[1].name or unitName
                return "[[" .. baseName .. "/" .. lang .. "|" .. displayName .. "]]"
            end
        end
        return match
    end)
    
    return processedText
end

return p