可在模块:Navplate SMW row display all/doc创建此模块的帮助文档
-- 自定义的trim函数
local function trim(s)
return (s:gsub("^%s*(.-)%s*$", "%1"))
end
local p = {}
local mw = require('mw')
p.cache = {} -- 初始化缓存
-- 新增函数用于获取页面的nodeicon属性
local function getnodeicon(pageName, frame)
local ask = '{{#ask:[[nodename::' .. pageName .. ']]|?nodeicon|mainlabel=-}}'
local result = frame:preprocess(ask)
return trim(result)
end
-- 新增函数用于从nodeicon值中提取src属性
local function extractSrcFromNodeicon(nodeicon)
local srcPattern = 'src="([^"]+)"'
local src = nodeicon:match(srcPattern)
return src
end
function p.navplateSmwRow(frame)
local args = frame:getParent().args
local categoryName = args[1]
local property = args[2]
local text = args[3]
local icon = args[4]
-- 使用缓存结果,减少查询
local cacheKey = categoryName .. (property or '') .. (text or '')
if p.cache[cacheKey] then
return p.cache[cacheKey]
end
-- 构建查询
local query = '[[Category:' .. mw.text.encode(categoryName) .. ']]'
if property and property ~= '' then
query = query .. '[[Has property::' .. mw.text.encode(property) .. ']]'
end
local ask = '{{#ask:' .. query ..
'|format=list' ..
'|link=all' ..
'|headers=hide' ..
'|searchlabel=' ..
'|class=smwlist' ..
'|sep=' ..
'}}'
-- 执行查询
local results = frame:preprocess(ask)
-- 缓存查询结果
p.cache[cacheKey] = results
-- 解析查询结果并提取图标src
local parsedResults = {}
for link in string.gmatch(results, '(%b<a></a>)') do
local pageName = link:match('title="([^"]+)"')
local trimmedPageName = trim(pageName)
local nodeicon = getnodeicon(trimmedPageName, frame) -- 获取页面的nodeicon属性
local imageSrc = ''
if nodeicon and nodeicon ~= '' then
-- 提取图标src
imageSrc = extractSrcFromNodeicon(nodeicon)
end
-- 将图标src嵌入到</a>标签之前
local modifiedLink = link:gsub('</a>', ' imagesrc="' .. imageSrc .. '"></a>')
table.insert(parsedResults, modifiedLink)
end
-- 格式化输出
local itemDiv = mw.html.create('div'):addClass('template-navplate-item')
local metadataAndTextDiv = mw.html.create('div'):addClass('template-navplate-item__label')
local metadata = mw.html.create('span'):addClass('metadata'):wikitext('[[File:' .. mw.text.encode(icon) .. '|20px|link=]] ' .. mw.text.encode(text))
metadataAndTextDiv:node(metadata)
local listDiv = mw.html.create('div'):addClass('template-navplate-item__list'):wikitext(table.concat(parsedResults, ''))
itemDiv
:node(metadataAndTextDiv)
:node(listDiv)
-- tostring之后进行修剪
local finalHtml = tostring(itemDiv:allDone())
finalHtml = trim(finalHtml)
return finalHtml
end
return p