Jump to content

Module:TemplateStructure

Revision as of 04:46, 16 February 2025 by MarkWD (talk | contribs)

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

local p = {}

--[[
    p.render(args, config)
    
    Renders a table using a modular, block-based approach via the HTML builder API.
    Instead of returning wiki table markup (which is later reinterpreted and escaped),
    this version builds and returns an mw.html object so that the output is treated as raw HTML.
    
    Parameters:
      args   - Table of template parameters (passed to each block function).
      config - Table containing configuration options:
          tableClass: (string) CSS class for the table.
                      Default: "template-table"
          tableAttrs: (table) A table of additional attributes for the table tag.
                      Default: { cellpadding = "2" }
          blocks:     (array) An ordered list of functions (blocks) that generate table rows.
                      Each block function should accept (args, config) and return an HTML fragment.
    
    Returns:
      An mw.html object representing the complete table.
    
    NOTE:
      This approach expects that the block functions produce HTML (or HTML fragments) rather than
      wiki markup. For example, instead of returning "{| ..." rows and "|}" markers, block functions
      should generate <tr>, <td>, or <th> elements. This change moves layout control into Lua so that
      MediaWiki’s parser won’t rewrap or escape the output.
]]
function p.render(args, config)
    config = config or {}
    local tableClass = config.tableClass or "template-table"
    local tableAttrs = config.tableAttrs or { cellpadding = "2" }
    local blocks = config.blocks or {}

    -- Create a table element using the HTML builder API.
    local tableEl = mw.html.create("table", tableAttrs)
    tableEl:attr("class", tableClass)
    
    -- Iterate over each block function, and insert its output as wikitext (which here is assumed to be safe HTML).
    for i, block in ipairs(blocks) do
        if type(block) == "function" then
            local blockOutput = block(args, config)
            if blockOutput and blockOutput ~= "" then
                tableEl:wikitext(blockOutput)
            end
        else
            mw.log("Warning: Block #" .. i .. " is not a function and will be skipped.")
        end
    end

    -- Return the mw.html object so that its output is not re-escaped.
    return tableEl
end

return p