Jump to content

Module:TrimArray

From PanEcoDevWiki

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

local p = {}

function p.links(frame)
    local input = frame.args[1] or ""
    local form = frame.args.form or ""
    local alt_forms_str = frame.args.alt_forms or ""
    local out = {}

    -- Build alt_forms table
    local alt_forms = {}
    for af in mw.text.gsplit(alt_forms_str, ",", true) do
        local trimmed = mw.text.trim(af)
        if trimmed ~= "" then
            table.insert(alt_forms, trimmed)
        end
    end

    -- Loop over each item
    for item in mw.text.gsplit(input, ",", true) do
        local trimmed_item = mw.text.trim(item)
        if trimmed_item ~= "" then
            local alt_form_params = ""
            if #alt_forms > 0 then
                for i, af in ipairs(alt_forms) do
                    alt_form_params = alt_form_params .. string.format("|alt_form[%d]=%s", i-1, af)
                end
            end

            -- Include form= only if alt_forms are empty
            local form_param = ""
            if #alt_forms == 0 and form ~= "" then
                form_param = string.format("|form=%s", form)
            end

            local template_str = string.format(
                "{{#formredlink:target=%s%s%s}}",
                trimmed_item,
                form_param,
                alt_form_params
            )

            table.insert(out, frame:preprocess(template_str) .. "<br>")
        end
    end

    return table.concat(out)
end

return p