Module:Foreach

From Holdfast: Nations At War
Jump to navigation Jump to search

Purpose

To repeatedly use a template for each argument in a pipe delimited list. The template handles up to 30 list items.

Coming here to use this template in a new page, or put it somewhere it hasn't been used before? Consider using Template:Fe instead!

Example

Create comma delimited links to each hook in a list

{{foreach|SeeHook|delim=, |ParserBeforeStrip|ParserAfterStrip}}

Usage

{{Foreach[|delim=delim]|templatename|item1[|item2]...}}
  • templatename - the name of a template that takes at least one parameter. Only the first parameter will be used, so the remaining parameters must be optional.
  • item1 - the first item to pass to the template, resulting in {{templatename|item1}}
  • item2,... - (optional) the second and following items to pass to the template, resulting in {{templatename|item2}}, etc.
  • delim - (optional) a delimiter that should be inserted between the list items after the template templatename has been applied to each

-- Replace http://www.mediawiki.org/wiki/Template:Foreach

local p = {}

function p.w(frame)
-- called from Template:Fe

    local pframe = frame:getParent() 
    local tplname = pframe.args[1]   
    local delim = pframe.args[2]
 
    r = ''
    for n,v in pframe:argumentPairs() do
       if n > 3 then
            r = r .. delim
        end
       if n>2 then r = r .. frame:expandTemplate{title = tplname, args = {v}} end
    end
    return r
end

function p.m(t,frame)
-- to be called from a module
-- at the top: p={foreach = require "Module:foreach"}
-- example: p.foreach.m({tplname,', ',item1,item3,item3},frame)

    r = ''
    tplname=t[1]
    delim=t[2]
    for n,v in ipairs(t) do
       if n > 3 then
            r = r .. delim
        end
     if n>2 then r = r .. frame:expandTemplate{title = tplname, args = {v}} end
    end
    return r
end

 
return p