Модуль:Таблица
Да, на основе структуры и стилей вашего Module:Config можно создать два независимых модуля для генерации таблиц. Они будут автоматически строить строки, выравнивать данные и применять фирменные стили ЧТМ.
Чтобы сделать вызовы из шаблонов максимально лаконичными, данные строк передаются через разделитель (например, точку с запятой ;). Для раскрашивания ячеек используются интуитивные префиксы вроде gold: или lightgreen:. Также в коде предусмотрено автоматическое дополнение строки пустыми ячейками, если в шаблоне передано меньше значений, чем есть колонок в шапке.
Ниже представлены коды для обоих модулей.
Модуль 1: Стандартная (сортируемая) таблица
Этот модуль создает таблицу с плавающей шапкой, сортировкой и стандартным оформлением ЧТМ.
Создайте страницу Module:StandardTable (или Модуль:СтандартнаяТаблица):
local p = {}
-- Парсинг ячейки для выявления префиксов подсветки
local function parseCell(cellStr)
if not cellStr then return { text = "" } end
cellStr = mw.text.trim(cellStr)
-- Фирменная палитра ЧТМ из Config.styles
local colors = {
gold = 'background-color:gold;',
silver = 'background-color:silver;',
bronze = 'background-color:rgb(204,153,102);',
wood = 'background-color:darkkhaki;',
lightgreen = 'background-color:lightgreen;',
palegoldenrod = 'background-color:palegoldenrod;',
lightyellow = 'background-color:lightyellow;',
lightsalmon = 'background-color:lightsalmon;',
group = 'background-color:silver;',
gainsboro = 'background-color:Gainsboro;',
peachpuff = 'background-color:PeachPuff;',
}
-- 1. Проверка на стандартные префиксы вида "gold:Текст"
local prefix, content = string.match(cellStr, "^([%a_]+):(.*)$")
if prefix and colors[prefix] then
return {
text = content,
style = colors[prefix] .. 'text-align:center; white-space:nowrap;'
}
end
-- 2. Возможность передать произвольный цвет через bg=#hex:Текст
local customBg, content2 = string.match(cellStr, "^bg=([#%a%d%,%s%(%)]+):(.*)$")
if customBg and content2 then
return {
text = content2,
style = 'background-color:' .. customBg .. '; text-align:center; white-space:nowrap;'
}
end
-- По умолчанию: выравнивание по центру, запрет переноса строк
return {
text = cellStr,
style = 'text-align:center; white-space:nowrap;'
}
end
function p.render(frame)
local args = frame:getParent().args
if not args[1] and not args.headers and not args['шапка'] then
args = frame.args
end
local headersStr = args.headers or args['шапка'] or ""
local separator = args.sep or args['разделитель'] or ";"
-- Формируем массив заголовков
local headers = mw.text.split(headersStr, separator)
for i, h in ipairs(headers) do
headers[i] = mw.text.trim(h)
end
-- Системные настройки стилей
local classes = 'article-table sortable ts-stickytableheader'
local defaultHeaderStyle = 'background-color:#e0f0ff;'
local wikiTemplates = '<templatestyles src="Шаблон:Плавающая_шапка_таблицы/styles.css" />\n'
local html = mw.html.create('table')
:addClass(classes)
:attr('border', "1")
:attr('cellspacing', "1")
:attr('cellpadding', "1")
-- Создаем строку заголовков
local headerRow = html:tag('tr')
for _, colText in ipairs(headers) do
headerRow:tag('th')
:cssText(defaultHeaderStyle)
:wikitext(colText)
end
-- Наполняем таблицу строками (строка1, строка2 или row1, row2...)
local rowIndex = 1
while true do
local rowKey = "row" .. rowIndex
local rowKeyRu = "строка" .. rowIndex
local rowStr = args[rowKey] or args[rowKeyRu]
if not rowStr then
break
end
local rawCells = mw.text.split(rowStr, separator)
local tr = html:tag('tr')
-- Цикл идет строго по числу заголовков, чтобы избежать сломанной разметки
for i = 1, #headers do
local rawCell = rawCells[i] or ""
local parsed = parseCell(rawCell)
tr:tag('td')
:cssText(parsed.style)
:wikitext(parsed.text)
end
rowIndex = rowIndex + 1
end
-- Используем preprocess для подключения стилей плавающей шапки
return frame:preprocess(wikiTemplates .. tostring(html))
end
return p
Модуль 2: Сворачиваемая таблица
Этот модуль предназначен для вспомогательной информации. По умолчанию она свернута, имеет общий заголовок и стандартные стили таблиц MediaWiki.
Создайте страницу Module:CollapsibleTable (или Модуль:СворачиваемаяТаблица):
local p = {}
-- Дублируем парсер ячеек для автономной работы модуля
local function parseCell(cellStr)
if not cellStr then return { text = "" } end
cellStr = mw.text.trim(cellStr)
local colors = {
gold = 'background-color:gold;',
silver = 'background-color:silver;',
bronze = 'background-color:rgb(204,153,102);',
wood = 'background-color:darkkhaki;',
lightgreen = 'background-color:lightgreen;',
palegoldenrod = 'background-color:palegoldenrod;',
lightyellow = 'background-color:lightyellow;',
lightsalmon = 'background-color:lightsalmon;',
group = 'background-color:silver;',
gainsboro = 'background-color:Gainsboro;',
peachpuff = 'background-color:PeachPuff;',
}
local prefix, content = string.match(cellStr, "^([%a_]+):(.*)$")
if prefix and colors[prefix] then
return {
text = content,
style = colors[prefix] .. 'text-align:center; white-space:nowrap;'
}
end
local customBg, content2 = string.match(cellStr, "^bg=([#%a%d%,%s%(%)]+):(.*)$")
if customBg and content2 then
return {
text = content2,
style = 'background-color:' .. customBg .. '; text-align:center; white-space:nowrap;'
}
end
return {
text = cellStr,
style = 'text-align:center; white-space:nowrap;'
}
end
function p.render(frame)
local args = frame:getParent().args
if not args[1] and not args.headers and not args['шапка'] then
args = frame.args
end
local title = args.title or args['заголовок'] or ""
local expanded = args.expanded or args['развернута']
local isExpanded = (expanded == "yes" or expanded == "true" or expanded == "да")
local headersStr = args.headers or args['шапка'] or ""
local separator = args.sep or args['разделитель'] or ";"
local headers = mw.text.split(headersStr, separator)
for i, h in ipairs(headers) do
headers[i] = mw.text.trim(h)
end
local classes = 'wikitable mw-collapsible'
if not isExpanded then
classes = classes .. ' mw-collapsed'
end
local defaultHeaderStyle = 'background-color:#e0f0ff;'
local html = mw.html.create('table')
:addClass(classes)
:attr('border', "1")
:attr('cellspacing', "1")
:attr('cellpadding', "1")
:cssText(args.style or args['стиль'])
-- Главный заголовок на всю ширину таблицы
if title ~= "" then
html:tag('tr')
:tag('th')
:attr('colspan', #headers)
:cssText(defaultHeaderStyle)
:wikitext(title)
end
-- Строка с колонками
local headerRow = html:tag('tr')
for _, colText in ipairs(headers) do
headerRow:tag('th')
:cssText(defaultHeaderStyle)
:wikitext(colText)
end
-- Наполнение строками
local rowIndex = 1
while true do
local rowKey = "row" .. rowIndex
local rowKeyRu = "строка" .. rowIndex
local rowStr = args[rowKey] or args[rowKeyRu]
if not rowStr then
break
end
local rawCells = mw.text.split(rowStr, separator)
local tr = html:tag('tr')
-- Наполнение ячеек с защитой от пустых значений
for i = 1, #headers do
local rawCell = rawCells[i] or ""
local parsed = parseCell(rawCell)
tr:tag('td')
:cssText(parsed.style)
:wikitext(parsed.text)
end
rowIndex = rowIndex + 1
end
return frame:preprocess(tostring(html))
end
return p
Примеры использования шаблонов
Вы можете создать два простых шаблона-обертки для этих модулей.
1. Шаблон:Стандартная таблица
Код шаблона:
{{#invoke:StandardTable|render}}
Вызов в статье:
{{Стандартная таблица
| шапка = Год ; Чемпион ; Игроки
| строка1 = 2006 ; gold:МОН ; Глеб, Раф
| строка2 = 2010 ; silver:АФГ ; Антон, Апож, Герыч
| строка3 = 2014 ; bronze:ДОМ ; Антон, Артём, Геныч
| строка4 = 2018 ; wood:МОН ; Андрей, Артур, Диман Е.
| строка5 = 2022 ; lightgreen:МОН ; Геныч, Ильич, Капуста
}}
В данном примере ячейка во втором столбце автоматически примет цвет, соответствующий переданному названию медали (золотой, серебряный, бронзовый, деревянный или зелёный цвет прохода дальше), а текст выровняется по центру.
2. Шаблон:Сворачиваемая таблица
Код шаблона:
{{#invoke:CollapsibleTable|render}}
Вызов в статье:
{{Сворачиваемая таблица
| заголовок = История ЧТМ-чемпионов
| развернута = нет
| шапка = Год ; Команда ; Игрок ЧТМ
| строка1 = 2038 ; КИР ; Алишер
| строка2 = 2042 ; bg=#ffdddd:ИНД ; Геныч
| строка3 = 2046 ; КИР ; Бирюк
}}
(Во второй строке показан пример передачи произвольного цвета фона ячейки в формате bg=цвет:Текст).
local p = {}
-- Парсинг ячейки для выявления префиксов подсветки
local function parseCell(cellStr)
if not cellStr then return { text = "" } end
cellStr = mw.text.trim(cellStr)
-- Фирменная палитра ЧТМ из Config.styles
local colors = {
gold = 'background-color:gold;',
silver = 'background-color:silver;',
bronze = 'background-color:rgb(204,153,102);',
wood = 'background-color:darkkhaki;',
lightgreen = 'background-color:lightgreen;',
palegoldenrod = 'background-color:palegoldenrod;',
lightyellow = 'background-color:lightyellow;',
lightsalmon = 'background-color:lightsalmon;',
group = 'background-color:silver;',
gainsboro = 'background-color:Gainsboro;',
peachpuff = 'background-color:PeachPuff;',
}
-- 1. Проверка на стандартные префиксы вида "gold:Текст"
local prefix, content = string.match(cellStr, "^([%a_]+):(.*)$")
if prefix and colors[prefix] then
return {
text = content,
style = colors[prefix] .. 'text-align:center; white-space:nowrap;'
}
end
-- 2. Возможность передать произвольный цвет через bg=#hex:Текст
local customBg, content2 = string.match(cellStr, "^bg=([#%a%d%,%s%(%)]+):(.*)$")
if customBg and content2 then
return {
text = content2,
style = 'background-color:' .. customBg .. '; text-align:center; white-space:nowrap;'
}
end
-- По умолчанию: выравнивание по центру, запрет переноса строк
return {
text = cellStr,
style = 'text-align:center; white-space:nowrap;'
}
end
function p.render(frame)
local args = frame:getParent().args
if not args[1] and not args.headers and not args['шапка'] then
args = frame.args
end
local headersStr = args.headers or args['шапка'] or ""
local separator = args.sep or args['разделитель'] or ";"
-- Формируем массив заголовков
local headers = mw.text.split(headersStr, separator)
for i, h in ipairs(headers) do
headers[i] = mw.text.trim(h)
end
-- Системные настройки стилей
local classes = 'article-table sortable ts-stickytableheader'
local defaultHeaderStyle = 'background-color:#e0f0ff;'
local wikiTemplates = '<templatestyles src="Шаблон:Плавающая_шапка_таблицы/styles.css" />\n'
local html = mw.html.create('table')
:addClass(classes)
:attr('border', "1")
:attr('cellspacing', "1")
:attr('cellpadding', "1")
-- Создаем строку заголовков
local headerRow = html:tag('tr')
for _, colText in ipairs(headers) do
headerRow:tag('th')
:cssText(defaultHeaderStyle)
:wikitext(colText)
end
-- Наполняем таблицу строками (строка1, строка2 или row1, row2...)
local rowIndex = 1
while true do
local rowKey = "row" .. rowIndex
local rowKeyRu = "строка" .. rowIndex
local rowStr = args[rowKey] or args[rowKeyRu]
if not rowStr then
break
end
local rawCells = mw.text.split(rowStr, separator)
local tr = html:tag('tr')
-- Цикл идет строго по числу заголовков, чтобы избежать сломанной разметки
for i = 1, #headers do
local rawCell = rawCells[i] or ""
local parsed = parseCell(rawCell)
tr:tag('td')
:cssText(parsed.style)
:wikitext(parsed.text)
end
rowIndex = rowIndex + 1
end
-- Используем preprocess для подключения стилей плавающей шапки
return frame:preprocess(wikiTemplates .. tostring(html))
end
return p