Jump to content

Module:WDfetch

From Amateur Theatre Wiki

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

-- This Lua module is designed for use in MediaWiki templates, 
-- particularly for MDwiki infoboxes, to retrieve and display clean values 
-- from Wikidata via the UnlinkedWikibase extension.
--
-- The module fetches the value of a specified Wikidata property (P-ID) 
-- using the {{#statements:}} parser function provided by the extension.
--
-- Example usage in a template:
-- {{#invoke:WDfetch|getvalue|pid=P12081}}
-- This retrieves and returns the value of the Wikidata property P12081 
-- for the current page's associated Wikibase item.

local p = {}

-- Function to fetch the value of a specified Wikidata property.
function p.getvalue(frame)
    -- Collect arguments from the calling frame
    local args = {}
    for k, v in pairs(frame:getParent().args) do
        if v ~= "" then args[k] = v end
    end
    for k, v in pairs(frame.args) do
        if v ~= "" then args[k] = v end
    end

    -- Get the property ID from the arguments
    local propertyId = args[1] or args.pid
    if not propertyId then
        return "Error: No property ID provided."
    end

    -- Use the #statements parser function to fetch the value
    local out = frame:callParserFunction("#statements", propertyId)

    -- If no result is found, return nil
    if string.sub(out, 1, 4) ~= "<!--" then
        -- Strip HTML markup: Remove <span> tags used by the extension
        local p1 = string.find(out, ">", 1, true) or 0
        local p2 = string.find(out, "<", -1, true) or #out + 1
        out = string.sub(out, p1 + 1, p2 - 1)

        -- Capitalize the first letter of the result
        out = out:gsub("^%l", string.upper)
    else
        out = nil
    end

    return out
end

return p