Module:CallTemplate
Appearance
The code for this module can be found below its documentation. You can edit the code, edit the documentation, or purge the cache.
This module and its documentation are slightly modified versions what Google's AI Overview returned for the prompt "simple Lua module to call a MediaWiki template for any number of input parameters". They will both be improved "soon".
Explanation
local p = {}: Initializes an empty tablepwhich will hold the module's functions.function p.call(frame): Defines a functioncallwithin the tablep. This function will be called by{{#invoke:CallTemplate|call}}. Theframeobject provides access to arguments and other MediaWiki functionalities.local args = frame.args: Retrieves the arguments passed to the{{#invoke:}}call as a table.local templateName = args[1]: Assumes the first positional argument is the name of the template to be called.local templateArgs = {}: Creates an empty table to store the arguments intended for the target template.for i, v in ipairs(args) do ... end: Iterates through the arguments passed to the module. It skips the first argument (the template name) and adds the rest totemplateArgs.local templateCall = "{{" .. templateName ... "}}": Constructs the wikitext string for the template call, dynamically adding the arguments.return frame:preprocess(templateCall): This is the core of calling the template.frame:preprocess()instructs MediaWiki to parse and expand the provided wikitext string, effectively calling the specified template with the collected arguments.
Usage in Wikitext
{{#invoke:CallTemplate|call|MyTemplate|Parameter1|Parameter2|NamedParameter=Value}}
This example would call Template:MyTemplate with Parameter1, Parameter2, and NamedParameter=Value as its arguments.
(end of Google's output)
Code
local p = {}
function p.call(frame)
local args = frame.args -- Get arguments passed to the #invoke call
local templateName = args[1] -- Assume the first argument is the template name
if not templateName then
return "Error: No template name provided."
end
local templateArgs = {}
for i, v in ipairs(args) do
if i > 1 then -- Skip the first argument (template name)
table.insert(templateArgs, v)
end
end
-- Construct the template call string
local templateCall = "{{" .. templateName
for i, v in ipairs(templateArgs) do
templateCall = templateCall .. "|" .. v
end
templateCall = templateCall .. "}}"
-- Expand the template call
return frame:preprocess(templateCall)
end
return p