Module:TableGenerator

Revision as of 21:33, 14 September 2024 by Sur (talk | contribs) (function docs)

Documentation for this module may be created at Module:TableGenerator/doc

local p = {}

--{{#invoke: TableGenerator | generateWikiTable | cols=3 | Item 1 | Item 2 | Item 3 | Item 4 | Item 5 }}
--creates
--Item 1, Item 2, Item 3
--Item 4, item 5
function p.generateWikiTable(frame)
    -- Get the arguments passed to the template
    local args = frame.args
    local cols = tonumber(args['cols']) or 3  -- Default number of columns is 3

    -- Initialize the table structure
    local result = '{| class="wikitable"\n'
    
    local count = 0
    for i, value in ipairs(args) do
        -- If the first argument is 'cols', skip it
        if i > 1 then
            -- If it's the start of a new row
            if count % cols == 0 then
                result = result .. '|-\n'
            end

            -- Add the value as a table cell
            result = result .. '| ' .. value .. '\n'
            count = count + 1
        end
    end
    
    -- Close any unfilled row
    if count % cols ~= 0 then
        result = result .. '|-\n'
    end

    -- Close the table
    result = result .. '|}'

    return result
end

--{{#invoke: TableGenerator | generateHtmlTable | cols=3 | Item 1 | Item 2 | Item 3 | Item 4 | Item 5 }}
--creates
--Item 1, Item 2, Item 3
--Item 4, item 5
function p.generateHtmlTable(frame)
    -- Get the arguments passed to the template
    local args = frame.args
    local cols = tonumber(args['cols']) or 3  -- Default number of columns is 3

    -- Initialize the HTML table structure
    local result = '<table class="wikitable">\n'
    
    local count = 0
    for i, value in ipairs(args) do
        -- If the first argument is 'cols', skip it
        if i > 1 then
            -- If it's the start of a new row
            if count % cols == 0 then
                result = result .. '  <tr>\n'
            end

            -- Add the value as a table cell
            result = result .. '    <td>' .. value .. '</td>\n'
            count = count + 1

            -- Close the row if we reached the end of a column set
            if count % cols == 0 then
                result = result .. '  </tr>\n'
            end
        end
    end
    
    -- Close any unfilled row
    if count % cols ~= 0 then
        result = result .. '  </tr>\n'
    end

    -- Close the table
    result = result .. '</table>'

    return result
end

return p