Модуль:Example
Реализация шаблона {{пример}}, см. его документацию. См. также
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('<nowiki>', ''):gsub('</nowiki>', '')
:gsub('<nowiki>', ''):gsub('</nowiki>', '')
:gsub('{{=}}', '=')
:gsub('{{=}}', '=')
:gsub('{{=}}', '=')
:gsub('{{=}}', '=')
:gsub('&', '&')
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 ' '
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
|
Index:
pl ar de en es fr it arz nl ja pt ceb sv uk vi war zh ru af ast az bg zh-min-nan bn be ca cs cy da et el eo eu fa gl ko hi hr id he ka la lv lt hu mk ms min no nn ce uz kk ro simple sk sl sr sh fi ta tt th tg azb tr ur zh-yue hy my ace als am an hyw ban bjn map-bms ba be-tarask bcl bpy bar bs br cv nv eml hif fo fy ga gd gu hak ha hsb io ig ilo ia ie os is jv kn ht ku ckb ky mrj lb lij li lmo mai mg ml zh-classical mr xmf mzn cdo mn nap new ne frr oc mhr or as pa pnb ps pms nds crh qu sa sah sco sq scn si sd szl su sw tl shn te bug vec vo wa wuu yi yo diq bat-smg zu lad kbd ang smn ab roa-rup frp arc gn av ay bh bi bo bxr cbk-zam co za dag ary se pdc dv dsb myv ext fur gv gag inh ki glk gan guw xal haw rw kbp pam csb kw km kv koi kg gom ks gcr lo lbe ltg lez nia ln jbo lg mt mi tw mwl mdf mnw nqo fj nah na nds-nl nrm nov om pi pag pap pfl pcd krc kaa ksh rm rue sm sat sc trv stq nso sn cu so srn kab roa-tara tet tpi to chr tum tk tyv udm ug vep fiu-vro vls wo xh zea ty ak bm ch ny ee ff got iu ik kl mad cr pih ami pwn pnt dz rmy rn sg st tn ss ti din chy ts kcg ve
Portal di Ensiklopedia Dunia