Module:DemoTemplate

From AusMetal Guide
Revision as of 18:42, 1 February 2022 by WikiAdmin (talk | contribs) (Created page with "require('Module:No globals') local newBuffer = require('Module:OutputBuffer') local mt = {} function mt.__index(t, title) return function(frame) local getBuffer, print, p...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Usage

Simply place "#invoke:DemoTemplate|" before a call to a template. For example, {{#invoke:DemoTemplate|Convert|10|km|nmi|abbr=off}} yields the following:

Lua error in package.lua at line 80: module 'Module:OutputBuffer' not found.

This module handles both named and positional parameters as well as equals signs in both parameter names and values correctly, so this (for example) will work: {{#invoke:DemoTemplate|1x|1=Some parameter with an = sign in it}}

Lua error in package.lua at line 80: module 'Module:OutputBuffer' not found.

Note, however, that pipes, curly braces, etc. are not currently handled correctly by this module, so this (for example) will not work correctly: {{#invoke:DemoTemplate|1x|foo{{!}}bar}}

Lua error in package.lua at line 80: module 'Module:OutputBuffer' not found.

require('Module:No globals')

local newBuffer = require('Module:OutputBuffer')
local mt = {}

function mt.__index(t, title)
	return function(frame)
		local getBuffer, print, printf = newBuffer()
		printf('{{%s', title)
		local ipairsArgs = {}
		for k,v in ipairs(frame.args) do
			if string.find(v, '=', 1, true) then
				break
			end
			ipairsArgs[k] = true
			printf('|%s', v)
		end
		for k,v in pairs(frame.args) do
			if not ipairsArgs[k] then
				printf('|%s=%s', string.gsub(k, '=', '{{=}}'), v)
			end
		end
		print('}}')
		local buffer = getBuffer()
		-- rather than calling expandTemplate with the title and args we have, call preprocess, so that our code example will always match our output, even in the cases of pipes or other things we should have escaped but didn't
		return string.format('<code>%s</code> &rarr; %s', mw.text.nowiki(buffer), frame:preprocess(buffer))
	end
end

return setmetatable({}, mt)