Difference between revisions of "Module:ApplyPattern"
Jump to navigation
Jump to search
m |
|||
(12 intermediate revisions by the same user not shown) | |||
Line 6: | Line 6: | ||
string.gsub(instr, pattern, function(c) fields[#fields+1] = c end) | string.gsub(instr, pattern, function(c) fields[#fields+1] = c end) | ||
return fields | return fields | ||
+ | end | ||
+ | |||
+ | function trim(s) | ||
+ | return (s:gsub("^%s*(.-)%s*$", "%1")) | ||
end | end | ||
Line 11: | Line 15: | ||
local list = frame.args[1] | local list = frame.args[1] | ||
local pattern = frame.args[2] | local pattern = frame.args[2] | ||
− | local result = | + | local result = {} |
+ | local sep = ',' | ||
+ | |||
+ | local newSep = frame.args[3] or '' | ||
+ | |||
+ | for key,entry in pairs(split(list,sep)) do | ||
+ | result[#result+1] = string.gsub(pattern, '%%pattern%%', trim(entry)) | ||
+ | end | ||
+ | |||
+ | return table.concat(result,newSep) | ||
+ | end | ||
+ | |||
+ | function p.applyTemplate(frame) | ||
+ | local list = frame.args[1] | ||
+ | local template = frame.args[2] | ||
+ | local substArg = frame.args[3] | ||
+ | |||
+ | |||
+ | local newSep = frame.args[4] or '' | ||
+ | |||
+ | local result = {} | ||
local sep = ',' | local sep = ',' | ||
for key,entry in pairs(split(list,sep)) do | for key,entry in pairs(split(list,sep)) do | ||
− | result = | + | local argTable = {} |
+ | argTable[substArg] = entry | ||
+ | result[#result+1] = frame:expandTemplate{title = template, args = argTable} | ||
end | end | ||
− | return result | + | return table.concat(result,newSep) |
end | end | ||
+ | |||
return p | return p |
Latest revision as of 19:04, 28 August 2019
Custom module to apply either some wiki markup or a template to each item in a comma delimited list. Look at Template:Class for examples.
local p = {} function split(instr,sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) string.gsub(instr, pattern, function(c) fields[#fields+1] = c end) return fields end function trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end function p.apply(frame) local list = frame.args[1] local pattern = frame.args[2] local result = {} local sep = ',' local newSep = frame.args[3] or '' for key,entry in pairs(split(list,sep)) do result[#result+1] = string.gsub(pattern, '%%pattern%%', trim(entry)) end return table.concat(result,newSep) end function p.applyTemplate(frame) local list = frame.args[1] local template = frame.args[2] local substArg = frame.args[3] local newSep = frame.args[4] or '' local result = {} local sep = ',' for key,entry in pairs(split(list,sep)) do local argTable = {} argTable[substArg] = entry result[#result+1] = frame:expandTemplate{title = template, args = argTable} end return table.concat(result,newSep) end return p