Module:Cite
武外梗百科 爱国好学自强图新的百科全书
更多操作
此模块的文档可以在Module:Cite/doc创建
local p = {}
function p.include(frame)
local page = mw.text.trim(frame.args[1] or frame.args.page or "")
local section = mw.text.trim(frame.args[2] or frame.args.section or "")
if page == "" or section == "" then
return ""
end
-- 获取标题对象(和你给的代码一致)
local title = mw.title.new(page)
if not title or not title.exists then
return ""
end
-- 获取完整 wikitext
local content = title:getContent()
if not content then
return ""
end
-- 转义段落名,防止正则炸
local safeSection = mw.ustring.gsub(
section,
"([%^%$%(%)%%%.%[%]%*%+%-%?])",
"%%%1"
)
-- 只匹配二级标题:== 段落 ==
local headerPattern = "\n==%s*" .. safeSection .. "%s*==%s*\n"
local startPos, endPos = mw.ustring.find(content, headerPattern)
-- 兼容段落在页面开头的情况
if not startPos then
headerPattern = "^==%s*" .. safeSection .. "%s*==%s*\n"
startPos, endPos = mw.ustring.find(content, headerPattern)
end
if not endPos then
return ""
end
-- 从标题结束后开始
local after = mw.ustring.sub(content, endPos + 1)
-- 找下一个二级标题
local nextHeader = mw.ustring.find(after, "\n==[^=]")
local body
if nextHeader then
body = mw.ustring.sub(after, 1, nextHeader - 1)
else
body = after
end
-- 原样返回,不清洗、不 trim
return string.format(
"'''原条目:[[%s]]'''\n\n%s",
page,
body
)
end
return p