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)
    local sparql = frame.args.sparql
    local title   = frame.args.title

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

    -- ✅ Correct HTTP module for MediaWiki Lua
    local http = require("http")  -- Only works if the Http extension is enabled

    -- Better: use mw.ext.externalData if available
    -- Best on Wikimedia wikis: use the built-in method below
    local url = "https://query.wikidata.org/sparql?format=json&query="
        .. mw.uri.encode(sparql)

    -- ✅ Use mw.ext.LuaHttp if installed
    local ok, result = pcall(function()
        return mw.ext.LuaHttp.request({
            url = url,
            method = "GET",
            headers = {
                ["Accept"] = "application/json",
                ["User-Agent"] = "MediaWiki Lua Module/1.0"
            }
        })
    end)

    if not ok or not result or result.code ~= 200 then
        return "⚠️ HTTP request failed. Check that LuaHttp extension is installed."
    end

    local data = mw.text.jsonDecode(result.body)
    local vars = data.head.vars
    local rows = data.results.bindings

    local html = {}

    if title and title ~= "" then
        table.insert(html, "=== " .. title .. " ===")
    end

    table.insert(html, '{| class="wikitable sortable"')

    -- Header row
    table.insert(html, "|-")
    for _, var in ipairs(vars) do
        table.insert(html, "! " .. var)
    end

    -- Data rows
    for _, row in ipairs(rows) do
        table.insert(html, "|-")
        for _, var in ipairs(vars) do
            local cell = (row[var] and row[var].value) or ""
            -- ✅ Render entity URIs as wiki links
            cell = cell:gsub("http://www%.wikidata%.org/entity/(Q%d+)", "[[wikidata:%1|%1]]")
            table.insert(html, "| " .. cell)
        end
    end

    table.insert(html, "|}")

    return table.concat(html, "\n")
end

return p