模块:Catnav

维基百科,自由的百科全书
(差异) ←上一修订 | 最后版本 (差异) | 下一修订→ (差异)
跳转到导航 跳转到搜索

local p = {}

function p.show(frame)
    local currentTitle = mw.title.getCurrentTitle()
    local args = frame:getParent().args
    local pagename = currentTitle.text

    -- 建立最外層的 div 容器
    local div = mw.html.create('div')
        :attr('id', 'topicpath')
        :attr('title', 'catnav')
        :addClass('catnav-topicpath')

    local items = {}
    local i = 1

    -- 無限延伸循環:依序讀取所有傳入參數
    while args[i] and mw.text.trim(args[i]) ~= "" do
        local val = mw.text.trim(args[i])
        local itemText = ""

        if val == "..." or val == "…" then
            itemText = val
        else
            -- 檢查該分類是否存在
            local catTitle = mw.title.new(val, 'Category')
            if catTitle and catTitle.exists then
                itemText = "[[:Category:" .. val .. "|" .. val .. "]]"
            else
                itemText = val
            end
        end

        table.insert(items, itemText)
        i = i + 1
    end

    -- 組合麵包屑字串
    local breadcrumb = ""
    if #items > 0 then
        breadcrumb = table.concat(items, " > ") .. " > " .. pagename
    else
        breadcrumb = pagename
    end

    div:wikitext(breadcrumb)

    -- 【動態偵測修改點】
    -- 獲取呼叫此模組的父級模板名稱(例如:Template:Catnav2)
    local parent = frame:getParent()
    local parentTitle = parent and parent:getTitle() or "Template:Catnav2"
    -- 自動組合成對應的 CSS 路徑(例如:Template:Catnav2/styles.css)
    local cssPage = parentTitle .. "/styles.css"

    -- 載入 TemplateStyles (CSS)
    local templatestyles = frame:extensionTag('templatestyles', '', { src = cssPage })
    
    -- 只有主命名空間 (0) 才會加入追蹤分類
    local category = ""
    if currentTitle.namespace == 0 then
        category = "[[Category:使用Catnav的页面]]"
    end

    return templatestyles .. tostring(div) .. category
end

return p