Module:Utilities: Difference between revisions

Jump to navigation Jump to search
m Added expand_templates util to help optimise template expansions
m Maintain output keys on expand_templates
Line 237: Line 237:


-- Expands multiple of the same template in a single preprocess call
-- Expands multiple of the same template in a single preprocess call
function p.expand_templates(frame, template_name, args_array)
-- Example:
-- expand_teampltes(frame, 'HeroIcon', {hero_atlas: {'Abrams'}, hero_bebop: {'Bebop'})
-- Returns {hero_atlas: <abrams_icon_template>, hero_bebop: <bebop_icon_template>, ...}
function p.expand_templates(frame, template_name, args_map)
    local keys = {}
     local strings = {}
     local strings = {}
     for i, args in ipairs(args_array) do
    for key, args in pairs(args_map) do
        keys[#keys + 1] = key
    end
     for i, key in ipairs(keys) do
        local args = args_map[key]
         local parts = {"{{", template_name, "|"}
         local parts = {"{{", template_name, "|"}
         for j, arg in ipairs(args) do
         for j, arg in ipairs(args) do
Line 248: Line 256:
         strings[i] = table.concat(parts)
         strings[i] = table.concat(parts)
     end
     end
     local expanded = frame:preprocess(table.concat(strings, "\x01"))
     local expanded = mw.text.split(
    return mw.text.split(expanded, "\x01")
        frame:preprocess(table.concat(strings, "\x01")), "\x01"
    )
    local result = {}
    for i, key in ipairs(keys) do
        result[key] = expanded[i]
    end
    return result
end
end


return p
return p