Module:Test2

From Elwiki
Revision as of 19:59, 25 April 2023 by Ritsu (talk | contribs)

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

local p = {}

function p.Patch(frame)
  local origTemplateRaw = frame.args.orig
  local origTemplate = mw.text.unstrip(origTemplateRaw)
  local newArgs = {}
  for k, v in pairs(frame.args) do
    if k ~= "orig" then
      newArgs[k] = v
    end
  end

  -- Extract the old arguments from the orig template
  local oldArgs = {}
  string.gsub(origTemplate, "%|%s*(%w+)%s*=%s*(.-)%s*", function(k, v)
    oldArgs[k] = v
  end)

  -- Merge the old and new arguments
  local mergedArgs = {}
  for k, v in pairs(oldArgs) do
    mergedArgs[k] = v
  end
  for k, v in pairs(newArgs) do
    mergedArgs[k] = v
  end

  -- Create the new template string with the merged arguments
  local newTemplate = "{{" .. string.match(origTemplate, "{{%s*(.-)%s*}}") .. "|"
  for k, v in pairs(mergedArgs) do
    newTemplate = newTemplate .. k .. "=" .. v .. "|"
  end
  newTemplate = newTemplate:sub(1, -2) .. "}}"

  -- Expand the new template
  local newTemplateExpanded = frame:expandTemplate{ title = mw.title.getCurrentTitle().text, args = mw.text.split(newTemplate, "|", true) }

  return newTemplateExpanded
end

return p