Модуль:Example: различия между версиями

Материал из Викимультии — энциклопедии мультипликации
Перейти к навигации Перейти к поиску
[непроверенная версия][отпатрулированная версия]
← Новая страница: «local p = {} -- используется для того, чтобы можно было удалять элементы из таблицы local function c…»
 
Нет описания правки
 
Строка 29: Строка 29:
local res = str
local res = str
str = mw.text.unstripNoWiki(str)
str = mw.text.unstripNoWiki(str)
str = string.gsub(str,'%[','[')
str = string.gsub(str, '%[', '[')
str = string.gsub(str,'%]',']')
str = string.gsub(str, '%]', ']')
str = string.gsub(str,'<','&lt;')
str = string.gsub(str, '<', '&lt;')
str = string.gsub(str,'>','&gt;')
str = string.gsub(str, '>', '&gt;')
str = string.gsub(str,'{','&#123;')
str = string.gsub(str, '{', '&#123;')
str = string.gsub(str,'}','&#125;')
str = string.gsub(str, '}', '&#125;')
str = string.gsub(str,'\'','&#39;')
str = string.gsub(str, '\'', '&#39;')
str = string.gsub(str, '"', '&quot;')
str = string.gsub(str, '(://)', '<span>%1</span>')
return str
return str
end
end
Строка 58: Строка 60:
local yesno = require('Module:Yesno')
local yesno = require('Module:Yesno')
local args = copy(getArgs(frame, {trim = false, removeBlanks = false})) --copy(frame.args)
local args = copy(getArgs(frame, {trim = false, removeBlanks = false})) --copy(frame.args)
local tag = args._tag or 'code'
local tag = args._tag
local container = args._container or nil
local container = args._container or nil
local sep = args._sep and args._sep .. ' ' or '&rarr; ' -- по умолчанию "→"
local ucFirst = yesno(args._u, false)
local link = yesno(args._link, false)
local link = yesno(args._link, false)
local sep = args._sep and args._sep .. ' '
local endl = args._endl or ''
local endl = args._endl or ''
local prefix = args._prefix or args['_pre-text'] or ''
local prefix = args._prefix or args['_pre-text'] or ''
local postfix = args._postfix or args['_post-text'] or ''
local postfix = args._postfix or args['_post-text'] or ''
local comment_sep = args._comment_sep or ' '    -- передаётся шаблоном {{стопка примеров}}, один разделитель на все примеры
local after = args._after or args._comment or '' -- полезно в шаблоне {{стопка примеров}} (это просто текст в конце)
local before = args._before or ''                -- полезно в шаблоне {{стопка примеров}} (это просто текст в начале)
local nobr = yesno(args._nobr, false)
local nobr = yesno(args._nobr, false)
local spaced = yesno(args._spaced, false)
local spaced = yesno(args._spaced, false)
local nocat = yesno(args._nocat, false)
local nocat = yesno(args._nocat, false)
local style = args._style
local style = args._style
if style == '' then
if (after ~= '') then
style = nil
after = comment_sep .. after
end
end
-- передаётся шаблоном {{стопка примеров}}, один разделитель на все примеры
local comment_sep = args._comment_sep
-- полезно в шаблоне {{стопка примеров}} (это просто текст в конце)
local after = args._after or args._comment
-- полезно в шаблоне {{стопка примеров}} (это просто текст в начале)
local before = args._before and args._before .. ' ' or ''
if style == 'pre' then
if style == 'pre' then
tag = nil
if not (tag or container) then
container = 'pre'
container = 'pre'
sep = '\n'
end
sep = sep or '\n'
elseif style == '*pre' then
elseif style == '*pre' then
tag = nil
if not (tag or container) then
container = '*pre'
container = '*pre'
sep = '\n'
end
sep = sep or '\n'
elseif style == 'pre↓' then
elseif style == 'pre↓' then
tag = nil
if not (tag or container) then
container = 'pre'
container = 'pre'
sep = '<div style="margin: -0.5em 50% 0.7em;"><big>↓</big></div>\n' --содержимое шаблона {{sp↓|50%||-0.5em}}
end
-- содержимое шаблона {{sp↓|50%||-0.5em}}
sep = sep or '<div style="margin:-0.5em 50% 0.7em;"><span style="font-size:150%;">↓</span></div>\n'
elseif style == '*pre↓' then
elseif style == '*pre↓' then
tag = nil
if not (tag or container) then
container = '*pre'
container = '*pre'
sep = '<div style="margin: -0.5em 50% 0.7em;"><big>↓</big></div>\n' --содержимое шаблона {{sp↓|50%||-0.5em}}
end
-- содержимое шаблона {{sp↓|50%||-0.5em}}
sep = sep or '<div style="margin:-0.5em 50% 0.7em;"><span style="font-size:150%;">↓</span></div>\n'
elseif style == 'wikitable' then
elseif style == 'wikitable' then
tag = 'tt'
if not (tag or container) then
sep = '\n|'
tag = 'kbd'
comment_sep = '\n|'
end
sep = sep or '\n| '
comment_sep = '\n| '
end
if not (tag or container) then
tag = 'code'
end
if not sep then
sep = '→ '
end
if not comment_sep then
comment_sep = ' &nbsp;'
end
if (after) then
if not style then
after = '<small>' .. after .. '</small>'
end
after = comment_sep .. after
end
if not after then
after = ''
end
end
local nwt = tag and mw.html.create(tag):tag(tag) --"no-wiki tag", внутри него шаблон не вызывается
local nwt
if nwt and nobr then
if tag then
nwt:css('white-space', 'nowrap')
nwt = mw.html.create(tag):tag(tag) -- "no-wiki tag", внутри него шаблон не вызывается
if nobr then
nwt:css('white-space', 'nowrap')
end
end
end
local content = nowiki(prefix) .. '{{' --для накопления содержимого тэга
local content = nowiki(prefix) .. '{{' -- для накопления содержимого тэга
local tname = args._template or args[1]
local tname = args._template or args[1]
if tname == nil then --если имя шаблона содержит знак "=" (работает, только если нет неименованных параметров)
if tname == nil then -- если имя шаблона содержит знак "=" (работает, только если нет неименованных параметров)
local nextfunc, static, cur = pairs(args)
local nextfunc, static, cur = pairs(args)
local k, v = nextfunc(static, cur)
local k, v = nextfunc(static, cur)
if k ~= nil and type(k) ~= 'number' and not k:find('^_') then --именованные параметры, исключая модификаторы внешнего вида
if k ~= nil and type(k) ~= 'number' and not k:find('^_') then -- именованные параметры, исключая модификаторы внешнего вида
tname = k .. "=" .. v
tname = k .. "=" .. v
args[k] = nil --больше этот параметр нам не пригодится
args[k] = nil --больше этот параметр нам не пригодится
end
end
end
end
if tname == '' or tname == nil then --при опущенном первом параметре берём имя шаблона из названия страницы
if tname == '' or tname == nil then -- при опущенном первом параметре берём имя шаблона из названия страницы
tname = mw.language.new('ru'):lcfirst(mw.title.getCurrentTitle().rootText)
local ru = mw.language.new('ru')
local currentTitle = mw.title.getCurrentTitle().rootText
if not ucFirst and
((ru:uc(currentTitle) ~= currentTitle and  -- названия со всеми заглавными буквами
not mw.ustring.match(currentTitle, '^[А-Яа-яA-Za-z]+:?[А-ЯA-Z]')  -- Книга:Литературное наследство, TranslateDate
) or
#currentTitle == 1
)
then
tname = ru:lcfirst(currentTitle)
else
tname = currentTitle
end
end
end
if args._template == nil then --имя вызываемого шаблона в неименованном первом параметре (или же взято из названия страницы или
                          --из именованного параметра в отсутствие неименованных — в следующей строчке вреда нет в любом случае),
-- Имя вызываемого шаблона в неименованном первом параметре (или же взято из названия страницы или
                          --больше его обрабатывать не надо
-- из именованного параметра в отсутствие неименованных — в следующей строчке вреда нет в любом случае),
-- больше его обрабатывать не надо
if args._template == nil then
table.remove(args,1)
table.remove(args,1)
end
end
Строка 131: Строка 181:
local targs, equals_pos, param, value, left_shift = {}, 0, '', '', 0
local targs, equals_pos, param, value, left_shift = {}, 0, '', '', 0
for k, v in pairs(args) do
for k, v in pairs(args) do
if type(k) == 'number' then --неименованные параметры
if type(k) == 'number' then -- неименованные параметры
equals_pos = v:find('=')
equals_pos = v:find('=')
if equals_pos and v:find('{{=}}') == equals_pos-2 then
if equals_pos and v:find('{{=}}') == equals_pos-2 then
equals_pos = nil
equals_pos = nil
end
end
if equals_pos then --содержащие "=" преобразуем в именованные
if equals_pos then -- содержащие "=" преобразуем в именованные
param = v:sub(1, equals_pos-1)
param = v:sub(1, equals_pos-1)
value = v:sub(equals_pos+1)
value = v:sub(equals_pos+1)
targs[param] = process_nowiki_equals(value)
targs[param] = process_nowiki_equals(value)
content = content .. (spaced and ' ' or '') .. '&#124;' .. param .. '=' .. nowiki(value) .. endl
content = content .. (spaced and ' ' or '') .. '&#124;' .. nowiki(param) .. '=' .. nowiki(value) .. endl
left_shift = left_shift+1 --переменная нужна, чтобы квазинумерованные параметры, переданные через "{{=}}",
left_shift = left_shift + 1 -- переменная нужна, чтобы квазинумерованные параметры, переданные через "{{=}}",
                          --не сбивали порядок
                            -- не сбивали порядок
else --истинно неименованные
else -- истинно неименованные
targs[k - left_shift] = process_nowiki_equals(v)
targs[k - left_shift] = process_nowiki_equals(v)
content = content .. (spaced and ' ' or '') .. '&#124;' .. nowiki(v) .. endl
content = content .. (spaced and ' ' or '') .. '&#124;' .. nowiki(v) .. endl
end
end
elseif not k:find('^_') then --именованные параметры, исключая модификаторы внешнего вида
elseif not k:find('^_') then -- именованные параметры, исключая модификаторы внешнего вида
targs[k] = process_nowiki_equals(v)
targs[k] = process_nowiki_equals(v)
content = content .. (spaced and ' ' or '') .. '&#124;' .. k .. '=' .. nowiki(v) .. endl
content = content .. (spaced and ' ' or '') .. '&#124;' .. nowiki(k) .. '=' .. nowiki(v) .. endl
end
end
end
if spaced then
content = content .. ' '
end
end
content = content .. '}}' .. nowiki(postfix)
content = content .. '}}' .. nowiki(postfix)

Текущая версия от 12:12, 7 августа 2019


Документация
local p = {}

-- используется для того, чтобы можно было удалять элементы из таблицы
local function copy(other)
	local res = {}
	for k,v in pairs(other) do
		res[k] = v
	end
	return res
end

-- вызов шаблона, при ошибке возвращает пустую строку
local function expand(frame, tname, targs)
	local success, result = pcall(
		frame.expandTemplate,
		frame,
		{title = tname, args = targs}
	)
	if success then
		return result
	else
		return ''
	end
	--return frame:expandTemplate({title = tname, args = args})
end

--предотвращает обработку вики-текста в отображении образца
local function nowiki(str)
	local res = str
	str = mw.text.unstripNoWiki(str)
	str = string.gsub(str, '%[', '[')
	str = string.gsub(str, '%]', ']')
	str = string.gsub(str, '<', '<')
	str = string.gsub(str, '>', '>')
	str = string.gsub(str, '{', '{')
	str = string.gsub(str, '}', '}')
	str = string.gsub(str, '\'', ''')
	str = string.gsub(str, '"', '"')
	str = string.gsub(str, '(://)', '<span>%1</span>')
	return str
end

--удаляет из параметров вписанные через HTML-сущности "<nowiki>" и заменяет "{{=}}" на "=" для вызова шаблона
local function process_nowiki_equals(str)
	str = str:gsub('<nowiki>', ''):gsub('</nowiki>', '')
			 :gsub('<nowiki>', ''):gsub('</nowiki>', '')
			 :gsub('{{=}}', '=')
			 :gsub('{{=}}', '=')
			 :gsub('{{=}}', '=')
			 :gsub('{{=}}', '=')
			 :gsub('&', '&')
	return str
end


function p.main(frame)
	if not getArgs then
		getArgs = require('Module:Arguments').getArgs
	end
	local yesno = require('Module:Yesno')
	local args = copy(getArgs(frame, {trim = false, removeBlanks = false})) --copy(frame.args)
	local tag = args._tag
	local container = args._container or nil
	local ucFirst = yesno(args._u, false)
	local link = yesno(args._link, false)
	local sep = args._sep and args._sep .. ' '
	local endl = args._endl or ''
	local prefix = args._prefix or args['_pre-text'] or ''
	local postfix = args._postfix or args['_post-text'] or ''
	local nobr = yesno(args._nobr, false)
	local spaced = yesno(args._spaced, false)
	local nocat = yesno(args._nocat, false)
	local style = args._style
	if style == '' then
		style = nil
	end
	-- передаётся шаблоном {{стопка примеров}}, один разделитель на все примеры
	local comment_sep = args._comment_sep
	-- полезно в шаблоне {{стопка примеров}} (это просто текст в конце)
	local after = args._after or args._comment
	-- полезно в шаблоне {{стопка примеров}} (это просто текст в начале)
	local before = args._before and args._before .. ' ' or ''
	
	if style == 'pre' then
		if not (tag or container) then
			container = 'pre'
		end
		sep = sep or '\n'
	elseif style == '*pre' then
		if not (tag or container) then
			container = '*pre'
		end
		sep = sep or '\n'
	elseif style == 'pre↓' then
		if not (tag or container) then
			container = 'pre'
		end
		-- содержимое шаблона {{sp↓|50%||-0.5em}}
		sep = sep or '<div style="margin:-0.5em 50% 0.7em;"><span style="font-size:150%;">↓</span></div>\n'
	elseif style == '*pre↓' then
		if not (tag or container) then
			container = '*pre'
		end
		-- содержимое шаблона {{sp↓|50%||-0.5em}}
		sep = sep or '<div style="margin:-0.5em 50% 0.7em;"><span style="font-size:150%;">↓</span></div>\n'
	elseif style == 'wikitable' then
		if not (tag or container) then
			tag = 'kbd'
		end
		sep = sep or '\n| '
		comment_sep = '\n| '
	end
	
	if not (tag or container) then
		tag = 'code'
	end
	if not sep then
		sep = '→ '
	end
	if not comment_sep then
		comment_sep = '  '
	end
	
	if (after) then
		if not style then
			after = '<small>' .. after .. '</small>'
		end
		after = comment_sep .. after
	end
	if not after then
		after = ''
	end
	
	local nwt
	if tag then
		nwt = mw.html.create(tag):tag(tag)  -- "no-wiki tag", внутри него шаблон не вызывается
		if nobr then
			nwt:css('white-space', 'nowrap')
		end
	end
	local content = nowiki(prefix) .. '{{'  -- для накопления содержимого тэга
	
	local tname = args._template or args[1]
	if tname == nil then  -- если имя шаблона содержит знак "=" (работает, только если нет неименованных параметров)
		local nextfunc, static, cur = pairs(args)
		local k, v = nextfunc(static, cur)
		if k ~= nil and type(k) ~= 'number' and not k:find('^_') then  -- именованные параметры, исключая модификаторы внешнего вида
			tname = k .. "=" .. v
			args[k] = nil --больше этот параметр нам не пригодится
		end
	end
	if tname == '' or tname == nil then  -- при опущенном первом параметре берём имя шаблона из названия страницы
		local ru = mw.language.new('ru')
		local currentTitle = mw.title.getCurrentTitle().rootText
		if not ucFirst and
			((ru:uc(currentTitle) ~= currentTitle and  -- названия со всеми заглавными буквами
				not mw.ustring.match(currentTitle, '^[А-Яа-яA-Za-z]+:?[А-ЯA-Z]')  -- Книга:Литературное наследство, TranslateDate
			) or
				#currentTitle == 1
			)
		then
			tname = ru:lcfirst(currentTitle)
		else
			tname = currentTitle
		end
	end
	
	-- Имя вызываемого шаблона в неименованном первом параметре (или же взято из названия страницы или
	-- из именованного параметра в отсутствие неименованных — в следующей строчке вреда нет в любом случае),
	-- больше его обрабатывать не надо
	if args._template == nil then
		table.remove(args,1)
	end
	if link then
		content = content .. '[[Шаблон:' .. tname .. '|' .. tname .. ']]'
	else
		content = content .. tname
	end
	content = content .. endl
	
	local targs, equals_pos, param, value, left_shift = {}, 0, '', '', 0
	for k, v in pairs(args) do
		if type(k) == 'number' then  -- неименованные параметры
			equals_pos = v:find('=')
			if equals_pos and v:find('{{=}}') == equals_pos-2 then
				equals_pos = nil
			end
			if equals_pos then  -- содержащие "=" преобразуем в именованные
				param = v:sub(1, equals_pos-1)
				value = v:sub(equals_pos+1)
				targs[param] = process_nowiki_equals(value)
				content = content .. (spaced and ' ' or '') .. '|' .. nowiki(param) .. '=' .. nowiki(value) .. endl
				left_shift = left_shift + 1  -- переменная нужна, чтобы квазинумерованные параметры, переданные через "{{=}}",
				                             -- не сбивали порядок
			else  -- истинно неименованные
				targs[k - left_shift] = process_nowiki_equals(v)
				content = content .. (spaced and ' ' or '') .. '|' .. nowiki(v) .. endl
			end
		elseif not k:find('^_') then  -- именованные параметры, исключая модификаторы внешнего вида
			targs[k] = process_nowiki_equals(v)
			content = content .. (spaced and ' ' or '') .. '|' .. nowiki(k) .. '=' .. nowiki(v) .. endl
		end
	end
	if spaced then
		content = content .. ' '
	end
	content = content .. '}}' .. nowiki(postfix)
	if container then
		local container_args = {}
		container_args[1] = content
		nwt = expand(frame, container, container_args)
	else
		nwt:wikitext(content):done()
	end
	
	if nocat then
		targs['nocat'] = 1
	end
	
	expand_result = tostring(expand(frame, tname, targs))
	if expand_result:sub(1, 2) == '{|' then
		sep = sep .. '\n'
	end
	
	return before .. tostring(nwt) .. ' ' .. sep .. prefix .. expand_result .. postfix .. after
end

return p