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

Материал из in.wiki
Перейти к навигации Перейти к поиску
(параметр spaced для отбивки каждого параметра пробелом в шаблонах типа t:книга)
м (1 версия импортирована)
 
(не показано 40 промежуточных версий 6 участников)
Строка 1: Строка 1:
 
local p = {}
 
local p = {}
 
-- используется для того, чтобы можно было удалять элементы из таблицы
 
local function copy(other)
 
local res = {}
 
for k,v in pairs(other) do
 
res[k] = v
 
end
 
return res
 
end
 
  
 
-- вызов шаблона, при ошибке возвращает пустую строку
 
-- вызов шаблона, при ошибке возвращает пустую строку
Строка 23: Строка 14:
 
end
 
end
 
--return frame:expandTemplate({title = tname, args = args})
 
--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,'<','&lt;')
 
str = string.gsub(str,'>','&gt;')
 
str = string.gsub(str,'{','&#123;')
 
str = string.gsub(str,'}','&#125;')
 
str = string.gsub(str,'\'','&#39;')
 
return str
 
 
end
 
end
  
Строка 47: Строка 24:
 
:gsub('{&#123;&#61;&#125;}', '=')
 
:gsub('{&#123;&#61;&#125;}', '=')
 
:gsub('{{=}}', '=')
 
:gsub('{{=}}', '=')
 +
:gsub('&amp;', '&')
 
return str
 
return str
 
end
 
end
 
  
 
function p.main(frame)
 
function p.main(frame)
if not getArgs then
+
local getArgs = require('Module:Arguments').getArgs
getArgs = require('Module:Arguments').getArgs
 
end
 
 
local yesno = require('Module:Yesno')
 
local yesno = require('Module:Yesno')
local args = copy(getArgs(frame, {trim = false, removeBlanks = false})) --copy(frame.args)
+
local template_code = require('Module:Template call code')._main
local tag =  args._tag or 'code'
+
local copy = require('Module:TableTools').shallowClone
local container = args._container or nil
+
local sep = args._sep and args._sep .. ' ' or '&rarr; ' -- по умолчанию "→"
+
local args = copy(getArgs(frame, {trim = false, removeBlanks = false}))
local link = yesno(args._link, false)
+
local alias =  args._alias
local endl = args._endl or ''
+
local tag = args._tag
local pre_text = args['_pre-text'] or args._prefix or ''
+
local sep = args._sep and args._sep .. ' '
local post_text = args['_post-text'] or args._postfix or  ''
+
local prefix = args._prefix or args['_pre-text'] or ''
local nobr = yesno(args._nobr, false)
+
local postfix = args._postfix or args['_post-text'] or ''
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
 +
style = nil
 +
end
 +
-- передаётся шаблоном {{стопка примеров}}, один разделитель на все примеры
 +
local comment_sep = args._comment_sep
 +
local comment = args._comment
 +
-- полезно в шаблоне {{стопка примеров}} (это просто текст в конце)
 +
local after = args._after or ''
 +
-- полезно в шаблоне {{стопка примеров}} (это просто текст в начале)
 +
local before = args._before and args._before .. ' ' or ''
 
 
if style == 'pre' then
+
if style == 'pre' or style == '*pre' or style == 'pre↓' or style == '*pre↓' then
tag = nil
+
tag = tag or 'pre'
container = 'pre'
 
sep = '\n'
 
elseif style == '*pre' then
 
tag = nil
 
container = '*pre'
 
sep = '\n'
 
elseif style == 'pre↓' then
 
tag = nil
 
container = 'pre'
 
sep = '<div style="margin-left: 50%; margin-bottom: 1em;"><big>↓</big></div>\n' --слегка изменённое содержимое шаблона t:sp↓
 
elseif style == '*pre↓' then
 
tag = nil
 
container = '*pre'
 
sep = '<div style="margin-left: 50%; margin-bottom: 1em;"><big>↓</big></div>\n' --слегка изменённое содержимое шаблона t:sp↓
 
elseif style == 'wikitable' then
 
tag = 'tt'
 
sep = '\n|'
 
 
end
 
end
local nwt = tag and mw.html.create(tag):tag(tag) --"no-wiki tag", внутри него шаблон не вызывается
+
if nwt and nobr then
+
if style == 'pre' or style == '*pre' then
nwt:css('white-space', 'nowrap')
+
sep = sep or '\n'
 +
elseif style == 'pre↓' or style == '*pre↓' then
 +
sep = sep or expand(frame, 'sp-down', {'', '-0.5em'})
 
end
 
end
local content = nowiki(pre_text) .. '{{' --для накопления содержимого тэга
+
 +
if style == '*pre' or style == '*pre↓' then
 +
before = '<ul><li>' .. expand(frame, 'chrome bullet hack', {}) .. before
 +
after = after .. '</li></ul>'
 +
end
 +
 +
if style == 'wikitable' then
 +
tag = tag or 'kbd'
 +
sep = sep or '\n| '
 +
comment_sep = '\n| '
 +
end
 +
 +
tag = tag or 'code'
 +
sep = sep or '→ '
 +
comment_sep = comment_sep or ' &nbsp;'
 +
 +
if comment then
 +
if not style then
 +
comment = '<small>' .. comment .. '</small>'
 +
end
 +
after = comment_sep .. comment .. after
 +
end
 +
 +
local _args = copy(args)
 +
_args._style = args._codestyle
 +
_args._comment = args._codecomment
 +
_args._tag = tag
 +
_args._prefix = prefix
 +
_args._postfix = postfix
 +
_args._nowiki = true
 +
if args._alias then
 +
table.insert(_args, 1, args._alias)
 +
elseif args._template then
 +
table.insert(_args, 1, args._template)
 +
end
 +
local nwt = template_code(_args, {withoutParams = false})
 +
 
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
 +
elseif not args._template then
 +
-- Имя вызываемого шаблона в неименованном первом параметре (или же взято из названия страницы или
 +
-- из именованного параметра в отсутствие неименованных — в следующей строчке вреда нет в любом случае),
 +
-- больше его обрабатывать не надо
 +
table.remove(args, 1)
 
end
 
end
if tname == '' or tname == nil then --при опущенном первом параметре берём имя шаблона из названия страницы
+
if tname == '' or tname == nil then -- при опущенном первом параметре берём имя шаблона из названия страницы
tname = mw.language.new('ru'):lcfirst(mw.title.getCurrentTitle().rootText)
+
tname = mw.title.getCurrentTitle().rootText
 
end
 
end
 +
 +
local targs, equals_pos, param, value, left_shift = {}, 0, '', '', 0
  
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, i = {}, 0, '', '', 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 -- неименованные параметры
if spaced then i = i+1 end
 
 
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 i == 1 and ' ' or '') .. '&#124;' .. nowiki(param) .. '=' .. nowiki(value) .. (spaced and ' ' or '') .. 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 .. '&#124;' .. nowiki(v) .. endl
 
 
end
 
end
elseif not k:find('^_') then --именованные параметры, исключая модификаторы внешнего вида
+
elseif not k:find('^_') then -- именованные параметры, исключая модификаторы внешнего вида
if spaced then i = i+1 end
 
 
targs[k] = process_nowiki_equals(v)
 
targs[k] = process_nowiki_equals(v)
content = content .. (spaced and i == 1 and ' ' or '') .. '&#124;' .. k .. '=' .. nowiki(v) .. (spaced and ' ' or '') .. endl
 
 
end
 
end
end
 
content = content .. '}}' .. nowiki(post_text)
 
if container then
 
local container_args = {}
 
container_args[1] = content
 
nwt = expand(frame, container, container_args)
 
else
 
nwt:wikitext(content):done()
 
 
end
 
end
 
 
if nocat then  
+
if nocat then
 
targs['nocat'] = 1
 
targs['nocat'] = 1
 
end
 
end
 
 
expand_result = tostring(expand(frame, tname, targs))
+
local expand_result = tostring(expand(frame, tname, targs))
if (expand_result:sub(1, 2) == '{|') then
+
if expand_result:sub(1, 2) == '{|' then
 
sep = sep .. '\n'
 
sep = sep .. '\n'
 
end
 
end
 
 
return tostring(nwt) .. ' ' .. sep .. pre_text .. expand_result .. post_text
+
return before .. tostring(nwt) .. ' ' .. sep .. prefix .. expand_result .. postfix .. after
 
end
 
end
  
 
return p
 
return p

Текущая версия от 11:55, 16 февраля 2025

Для документации этого модуля может быть создана страница Модуль:Example/doc

local p = {}

-- вызов шаблона, при ошибке возвращает пустую строку
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

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

function p.main(frame)
	local getArgs = require('Module:Arguments').getArgs
	local yesno = require('Module:Yesno')
	local template_code = require('Module:Template call code')._main
	local copy = require('Module:TableTools').shallowClone
	
	local args = copy(getArgs(frame, {trim = false, removeBlanks = false}))
	local alias =  args._alias
	local tag = args._tag
	local sep = args._sep and args._sep .. ' '
	local prefix = args._prefix or args['_pre-text'] or ''
	local postfix = args._postfix or args['_post-text'] or ''
	local nocat = yesno(args._nocat, false)
	local style = args._style
	if style == '' then
		style = nil
	end
	-- передаётся шаблоном {{стопка примеров}}, один разделитель на все примеры
	local comment_sep = args._comment_sep
	local comment = args._comment
	-- полезно в шаблоне {{стопка примеров}} (это просто текст в конце)
	local after = args._after or ''
	-- полезно в шаблоне {{стопка примеров}} (это просто текст в начале)
	local before = args._before and args._before .. ' ' or ''
	
	if style == 'pre' or style == '*pre' or style == 'pre↓' or style == '*pre↓' then
		tag = tag or 'pre'
	end
	
	if style == 'pre' or style == '*pre' then
		sep = sep or '\n'
	elseif style == 'pre↓' or style == '*pre↓' then
		sep = sep or expand(frame, 'sp-down', {'', '-0.5em'})
	end
	
	if style == '*pre' or style == '*pre↓' then
		before = '<ul><li>' .. expand(frame, 'chrome bullet hack', {}) .. before
		after = after .. '</li></ul>'
	end
	
	if style == 'wikitable' then
		tag = tag or 'kbd'
		sep = sep or '\n| '
		comment_sep = '\n| '
	end
	
	tag = tag or 'code'
	sep = sep or '→ '
	comment_sep = comment_sep or ' &nbsp;'
	
	if comment then
		if not style then
			comment = '<small>' .. comment .. '</small>'
		end
		after = comment_sep .. comment .. after
	end
	
	local _args = copy(args)
	_args._style = args._codestyle
	_args._comment = args._codecomment
	_args._tag = tag
	_args._prefix = prefix
	_args._postfix = postfix
	_args._nowiki = true
	if args._alias then
		table.insert(_args, 1, args._alias)
	elseif args._template then
		table.insert(_args, 1, args._template)
	end
	local nwt = template_code(_args, {withoutParams = false})
	
	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
	elseif not args._template then
		-- Имя вызываемого шаблона в неименованном первом параметре (или же взято из названия страницы или
		-- из именованного параметра в отсутствие неименованных — в следующей строчке вреда нет в любом случае),
		-- больше его обрабатывать не надо
		table.remove(args, 1)
	end
	if tname == '' or tname == nil then  -- при опущенном первом параметре берём имя шаблона из названия страницы
		tname = mw.title.getCurrentTitle().rootText
	end
	
	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)
				left_shift = left_shift + 1  -- переменная нужна, чтобы квазинумерованные параметры, переданные через "{{=}}",
				                             -- не сбивали порядок
			else  -- истинно неименованные
				targs[k - left_shift] = process_nowiki_equals(v)
			end
		elseif not k:find('^_') then  -- именованные параметры, исключая модификаторы внешнего вида
			targs[k] = process_nowiki_equals(v)
		end
	end
	
	if nocat then
		targs['nocat'] = 1
	end
	
	local 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