“模块:GetParentSec”的版本间的差异
跳到导航
跳到搜索
(与大鲸鱼斗智斗勇) |
|||
| 第17行: | 第17行: | ||
-- 检查是否包含我们的模板 | -- 检查是否包含我们的模板 | ||
| − | if name:find("{{ | + | if name:find("{{GetParentSec}}") then |
-- 返回栈顶的父章节(如果有) | -- 返回栈顶的父章节(如果有) | ||
found = true | found = true | ||
2025年4月30日 (三) 21:36的版本
此模块的文档可以在模块:GetParentSec/doc创建
local p = {}
function p.getParentSection(frame)
-- 获取当前页面原始内容
local currentTitle = mw.title.getCurrentTitle()
local content = currentTitle:getContent() or ""
-- 解析章节结构
local stack = {} -- 用于跟踪章节层级
local found = false
for line in content:gmatch("[^\r\n]+") do
local level, name = line:match("^(=+)([^=]+)=+$")
if level then
level = #level
name = mw.text.trim(name)
-- 检查是否包含我们的模板
if name:find("{{GetParentSec}}") then
-- 返回栈顶的父章节(如果有)
found = true
break
end
-- 维护章节栈
while #stack > 0 and stack[#stack].level >= level do
table.remove(stack)
end
table.insert(stack, {level = level, name = name})
end
end
if found and #stack > 0 then
return stack[#stack].name
else
return "" -- 返回空字符串避免破坏标题格式
end
end
return p