模块:Navplate SMW row

来自决策链云智库
Zeroclanzhang讨论 | 贡献2024年1月24日 (三) 18:46的版本

可在模块:Navplate SMW row/doc创建此模块的帮助文档

-- Module:NavplateSMWRow
local p = {}
local mw = require('mw')

p.cache = {} -- 初始化缓存

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 .. '[[' .. mw.text.encode(property) .. ']]'
    end

    -- 转换查询为#ask解析器函数的形式,改为list格式,用'|'进行间隔
    local ask = '{{#ask:' .. query ..
            '|format=list' ..
            '|link=all' ..
            '|headers=hide' ..
            '|searchlabel=' ..
            '|class=smwlist' ..
            '|sep=' ..  -- 指定列表项分隔符为逗号
            '}}'

    -- 执行查询
    local results = frame:preprocess(ask)

    -- 缓存查询结果
    p.cache[cacheKey] = results

    -- 格式化输出
    local itemDiv = mw.html.create('div'):addClass('template-navplate-item')
    local categoryDiv = mw.html.create('div'):addClass('template-navplate-item__category')
    local metadata = mw.html.create('div'):addClass('metadata')
    local listDiv = mw.html.create('div'):addClass('template-navplate-item__list')

    -- 添加图标和类别
    metadata:wikitext('[[File:' .. mw.text.encode(icon) .. '|20px|link=]] ')
    local textLink = mw.html.create('span')  -- 定义textLink变量
    textLink:wikitext('[[' .. mw.text.encode(text) .. ']]')

    -- 添加查询结果
    listDiv:wikitext(results)

    -- 逐步组合所有部分
    categoryDiv
            :node(metadata) 
            :node(textLink)
    itemDiv
            :node(categoryDiv)
            :node(listDiv)

    return tostring(itemDiv:allDone())
end

return p