Module:SemanticAnnotations: Difference between revisions

// via Wikitext Extension for VSCode
 
// via Wikitext Extension for VSCode
Line 161: Line 161:
     -- Generate and return the annotations
     -- Generate and return the annotations
     return p.generateAnnotations(parentArgs, mappings, options)
     return p.generateAnnotations(parentArgs, mappings, options)
end
--[[
    p.setSemanticProperties(args, mappings, options)
   
    Sets semantic properties using the native mw.smw API when available,
    falling back to the parser function approach if not.
   
    Parameters:
      args    - Table of template parameters.
      mappings - Table with mappings from semantic properties to template parameters.
      options  - Optional configuration options (same as generateAnnotations).
   
    Returns:
      Empty string if properties were set via mw.smw, otherwise the generated annotations.
]]
function p.setSemanticProperties(args, mappings, options)
    -- Check if mw.smw is available
    if not mw.smw then
        -- Fall back to the parser function approach if mw.smw is not available
        return p.generateAnnotations(args, mappings, options)
    end
   
    options = options or {}
    local transform = options.transform or {}
    local default = options.default or {}
    local prefix = options.prefix or ""
   
    -- Build the property table for mw.smw.set
    local properties = {}
   
    -- Process regular mappings
    for property, param in pairs(mappings) do
        local fullPropertyName = prefix .. property
        local value = args[param]
       
        -- Apply transform if one exists
        if value and transform[property] then
            value = transform[property](value)
        end
       
        -- Use value if it exists, otherwise use default
        if value and value ~= "" then
            properties[fullPropertyName] = value
        elseif default[property] then
            properties[fullPropertyName] = default[property]
        end
    end
   
    -- Only set properties if we have some
    if next(properties) then
        -- Set the properties using the native SMW interface
        local success, result = pcall(function()
            return mw.smw.set(properties)
        end)
       
        -- If successful, return empty string (properties are set behind the scenes)
        -- If failed, fall back to parser function approach
        if success then
            return ""
        else
            return p.generateAnnotations(args, mappings, options)
        end
    end
   
    return ""
end
end


return p
return p