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