Module:PageSummary
武外梗百科 爱国好学自强图新的百科全书
更多操作
此模块的文档可以在Module:PageSummary/doc创建
function p.getSummaryAndImage(frame)
local pageName = mw.text.trim(frame.args[1] or "")
if pageName == "" then return "" end
local title = mw.title.new(pageName)
if not title or not title.exists then return "" end
local content = title:getContent()
if not content or content == "" then return "" end
local rawExcerpt = mw.ustring.sub(content, 1, 600) or "" -- 再加大范围
-- 严格提取图片文件名(只取有效部分)
local firstImage = nil
for _, prefix in ipairs({"File:", "文件:", "Image:", "图像:"}) do
firstImage = mw.ustring.match(rawExcerpt, "%[%[" .. prefix .. "([^|%]]+)%f[|%]]")
if firstImage then break end
end
-- 如果匹配失败,不 fallback 到页面名,保持 nil
if firstImage then
firstImage = mw.text.trim(firstImage)
-- 清理非法字符(防止编码损坏)
firstImage = mw.ustring.gsub(firstImage, "[%z%s<>\"]+", "")
-- 太短或空字符串视为无效
if mw.ustring.len(firstImage) < 5 then
firstImage = nil
end
end
local step1 = stripImages(rawExcerpt) or ""
local cleanText = cleanFinal(step1) or ""
local targetLen = 120
local summary = cleanText:sub(1, targetLen * 2) or ""
local ulen = mw.ustring.len(summary) or 0
if ulen > targetLen then
summary = mw.ustring.sub(summary, 1, targetLen) or ""
local rev = summary:reverse()
local lastBreak = rev:find("[ %s%p,。!?;:,…]") or 1
if lastBreak > 1 and lastBreak < 20 then
summary = mw.ustring.sub(summary, 1, #summary - lastBreak + 1) or ""
end
summary = mw.text.trim(summary) .. "..."
end
summary = mw.text.trim(summary)
-- 构建 HTML
local container = mw.html.create('div')
:css('margin-bottom', '25px')
:css('display', 'flow-root')
-- 标题
container:tag('div')
:css('font-size', '1.3em')
:css('font-weight', 'bold')
:css('margin-bottom', '6px')
:css('border-bottom', '1px solid #eee')
:wikitext('[[' .. pageName .. ']]')
local textDiv = container:tag('div')
:css('line-height', '1.6')
:css('color', '#222')
:css('font-size', '14px')
-- 只有当 firstImage 是有效字符串时才添加图片(避免任何泄漏)
if firstImage and firstImage ~= "" and mw.ustring.find(firstImage, ":") then
local imgWikitext = '[[' .. firstImage .. '|120px|right|link=' .. pageName .. ']]'
textDiv:wikitext(imgWikitext)
end
textDiv:wikitext(summary)
return tostring(container)
end