Module:表格

来自缺氧 Wiki
跳转到导航 跳转到搜索
-- Module:表格
local p = {}
local fstr = mw.ustring.format -- shortcut for formattig a string

-- test by: = p.table({{1,2,3},{4,5,6}})
-- test by: = p.table({{1,2,3},{4,{5, {['data-sort-value'] = 6}},6}})
function p.table(tb, args)
    args = type(args) == "table" and args or {}

    local out = {}

    for _, row in ipairs(tb) do
        local rowOut = {}
        for i, cell in ipairs(row) do
            local content
            local attrs
            if type(cell) == "table" then
                content = cell[1]
                attrs = mw.clone(cell[2])
            else
                content = cell
                attrs = {}
            end
            local sty = args[fstr("style col %d", i)]
            if sty ~= nil and attrs.style == nil then
                attrs.style = sty
            end
            local cellCode = ""
            if type(next(attrs)) ~= "nil" then
                cellCode = '| '
                for k, v in pairs(attrs) do
                    cellCode = fstr('%s%s="%s" ', cellCode, k, v)
                end
            end
            cellCode = fstr('%s| %s\n', cellCode, content)
            table.insert(rowOut, cellCode)
        end
        table.insert(out, fstr("|-\n%s", table.concat(rowOut, "")))
    end

    return mw.getCurrentFrame():preprocess(table.concat(out, ""))
end

function p.error(msg, args)
    local out = "|-\n|"
    local nCol = args and args.nCol and tonumber(args.nCol)
    if nCol then out = fstr('%s colspan="%d" |', out, nCol) end
    return fstr("%s(%s)", out, msg)
end

function p.test(frame) return p.table({{1, 2, 3}, {4, 5, 6}}) end

return p