Loading
  • 21 Aug, 2019

  • By, Wikipedia

Module:For Nowiki

This module implements a foreach loop that can be used from wikitext. It exports two functions:

  • main - Implements {{For nowiki}}, which can be used with explicitly provided parameters. Should not be called diretly.
  • template - Designed to be used from within other templates. It takes explicit configuration parameters but it uses parameters passed to the parent frame (the template) for all others. Should be called directly.

Usage

{{#invoke:For nowiki|template|separator|<nowiki>wikitext</nowiki>|offset=offset}}
  • separator and wikitext function the same as described in Template:For nowiki/doc#Usage.
  • offset is the offset of the first argument to process. Defaults to 0, which means the |1= parameter passed to the template is the first parameter processed.

Example

If you have a template _TEMPLATE_:

{{#invoke:For nowiki|template|
|<nowiki>* {{{i}}} is {{{1}}}. Next is {{#expr:{{{i}}} + 1}}.</nowiki>}}

Then calling:

{{_TEMPLATE_|A|B|Foo|Orange}}

Would produce:

  • 1 is A. Next is 2.
  • 2 is B. Next is 3.
  • 3 is Foo. Next is 4.
  • 4 is Orange. Next is 5.

See also

local p = {}

local function doLoop(frame, args, code, sep, offset, argstosub)
	local result = {}
	code = mw.text.unstripNoWiki(code)
	code = code:gsub('&lt;', '<'):gsub('&gt;', '>')
	for i, value in ipairs(args) do
		if i > offset then
			argstosub["i"] = i - offset
			argstosub["1"] = value
			local actualCode = code:gsub("{{{([^{}|]*)|?[^{}]*}}}", argstosub)
			table.insert(result, frame:preprocess(actualCode))
		end
	end
	return table.concat(result, sep)
end

function p.main(frame)
	local args = frame:getParent().args
	local sep = args[1]
	local code = args.code or args[2]
	local offset = args.code and 1 or 2
	local start = args.start or 1
	local argstosub = {}
	for key, value in pairs(args) do
		if not tonumber(key) and key ~= "i" and key ~= "count" then
			argstosub[key] = value
		end
	end
	local countArg = args.count and tonumber(args.count);
	if countArg then
		offset = 0
		args = {}
		for i = 1, countArg do
		   args[i] = i + start - 1
		end
	end
	return doLoop(frame, args, code, sep, offset, argstosub)
end
function p.template(frame) 
	local sep = frame.args[1]
	local code = frame.args[2] or frame.args.code
	local offset = tonumber(frame.args.offset) or 0
	return doLoop(frame:getParent(), frame:getParent().args, code, sep, offset, {})
end
return p