Module:WikidataTable

De Wikiromandie.org
Aller à la navigation Aller à la recherche

La documentation pour ce module peut être créée à Module:WikidataTable/doc

local p = {}

function p.render(frame)
    -- Fetch arguments, defaulting to empty string
    local sparql = frame.args.sparql or ""
    local title  = frame.args.title  or ""

    -- Use frame:getParent() as fallback if parameters are passed directly to the template
    if sparql == "" and frame:getParent() then
        sparql = frame:getParent().args.sparql or ""
        title  = frame:getParent().args.title  or ""
    end

    if sparql == "" then
        return "⚠️ No SPARQL query provided."
    end

    local function cleanAndEncode(s)
        -- 1. Replace UTF-8 non-breaking spaces (\194\160) with standard spaces
        s = s:gsub('\194\160', ' ')
        
        -- 2. Collapse all newlines, tabs, and multiple spaces into single standard spaces
        s = s:gsub('%s+', ' ')
        
        -- 3. Trim leading and trailing whitespace
        s = mw.text.trim(s)

        -- 4. Escape special HTML attribute characters
        return s:gsub('&', '&')
                :gsub('"', '"')
                :gsub('<', '&lt;')
                :gsub('>', '&gt;')
    end

    local cleanSparql = cleanAndEncode(sparql)
    local cleanTitle  = cleanAndEncode(title)

    -- Return compact HTML output without outer whitespace or trailing newlines
    return string.format(
        '<div class="wikidata-sparql-table" data-sparql="%s" data-title="%s"></div>',
        cleanSparql,
        cleanTitle
    )
end

return p