Module:PageSummary
武外梗百科 爱国好学自强图新的百科全书
更多操作
此模块的文档可以在Module:PageSummary/doc创建
local p = {}
function p.getSummaryAndImage(frame)
local pageName = frame.args[1] or ""
local title = mw.title.new(pageName)
if not title or not title.exists then return "页面不存在" end
local content = title:getContent()
-- 1. 提取第一张图(用于单独在右侧显示)
local firstImage = string.match(content, "%[%[([Ff]ile:.-)[|%]]") or
string.match(content, "%[%[([Ii]mage:.-)[|%]]") or
string.match(content, "%[%[(文件:.-)[|%]]") or
string.match(content, "%[%[(图像:.-)[|%]]")
-- 2. 彻底清理正文(去除所有图片、模板、引用)
local cleanText = content
-- 核心:彻底去除摘要文本中所有的图片标记
-- 使用更严谨的匹配:从 [[File: 开始,匹配到第一个不被嵌套的 ]]
cleanText = string.gsub(cleanText, "%[%[[Ff]ile:.-%]%]", "")
cleanText = string.gsub(cleanText, "%[%[[Ii]mage:.-%]%]", "")
cleanText = string.gsub(cleanText, "%[%[文件:.-%]%]", "")
cleanText = string.gsub(cleanText, "%[%[图像:.-%]%]", "")
-- 移除其余干扰项
cleanText = string.gsub(cleanText, "<ref.-</ref>", "")
cleanText = string.gsub(cleanText, "<ref.->", "")
cleanText = string.gsub(cleanText, "<!%-%-.-%-%->", "")
local limit = 10
while string.find(cleanText, "{{.-}}") and limit > 0 do
cleanText = string.gsub(cleanText, "{{[^{}]+}}", "")
limit = limit - 1
end
cleanText = mw.text.trim(cleanText)
cleanText = string.gsub(cleanText, "\n", " ")
-- 3. 延展截断逻辑
local targetLen = 100
local summary = ""
if mw.ustring.len(cleanText) <= targetLen then
summary = cleanText
else
summary = mw.ustring.sub(cleanText, 1, targetLen)
local restText = mw.ustring.sub(cleanText, targetLen + 1)
local lastOpen = 0
local lastClose = 0
local tempPos = 0
while true do
local found = string.find(summary, "%[%[", tempPos + 1)
if not found then break end
lastOpen = found
tempPos = found
end
tempPos = 0
while true do
local found = string.find(summary, "%]%]", tempPos + 1)
if not found then break end
lastClose = found
tempPos = found
end
if lastOpen > lastClose then
local endOfLink = string.find(restText, "%]%]")
if endOfLink then
summary = summary .. string.sub(restText, 1, endOfLink + 1)
end
end
summary = summary .. "..."
end
-- 4. 无背景、维基样式的渲染
local container = mw.html.create('div')
:css({
['margin'] = '15px 0',
['padding'] = '0',
['background'] = 'transparent', -- 去除背景
['display'] = 'flow-root' -- 确保包裹右侧浮动图片
})
-- 使用维基标准 thumb 样式,会自动处理边框和间距
if firstImage then
container:wikitext('[[' .. firstImage .. '|thumb|150px|right|link=' .. pageName .. ']]')
end
-- 标题:维基百科标准 h2 风格
container:tag('div')
:css({
['font-size'] = '1.5em',
['font-family'] = '"Linux Libertine", "Georgia", "Times", serif',
['font-weight'] = 'normal',
['margin-bottom'] = '0.25em',
['border-bottom'] = '1px solid #a2a9b1', -- 维基标准下划线
['padding-bottom'] = '0'
})
:wikitext('[[' .. pageName .. ']]')
-- 摘要
container:tag('div')
:css({
['line-height'] = '1.6',
['color'] = '#202122'
})
:wikitext(summary)
return tostring(container)
end
return p