“模块:GetParentSec”的版本间的差异
跳到导航
跳到搜索
| 第1行: | 第1行: | ||
local p = {} | local p = {} | ||
| − | function p. | + | function p.getParentSection(frame) |
-- 获取当前页面内容 | -- 获取当前页面内容 | ||
local currentTitle = mw.title.getCurrentTitle() | local currentTitle = mw.title.getCurrentTitle() | ||
2025年4月30日 (三) 21:38的版本
此模块的文档可以在模块:GetParentSec/doc创建
local p = {}
function p.getParentSection(frame)
-- 获取当前页面内容
local currentTitle = mw.title.getCurrentTitle()
local content = currentTitle:getContent() or ""
-- 解析章节结构
local parentStack = {} -- 用于维护父章节层级
local result = nil
for line in content:gmatch("[^\r\n]+") do
-- 匹配章节标题
local level, title = line:match("^(=+)([^=]+)=+$")
if level then
level = #level -- 计算标题级别
title = mw.text.trim(title) -- 去除前后空格
-- 检查是否包含我们的模板
if title:find("{{GetParentSec}}") then
-- 找到模板调用,获取最近的父章节
if #parentStack > 0 then
result = parentStack[#parentStack].title
else
result = "" -- 没有父章节
end
end
-- 维护父章节栈
while #parentStack > 0 and parentStack[#parentStack].level >= level do
table.remove(parentStack)
end
table.insert(parentStack, {level = level, title = title})
end
end
return result or ""
end
return p