Module:Context-link

From The Satanic Wiki
Revision as of 03:13, 23 December 2019 by Mediawiki>Technobliterator (minor thing, but oxford comma)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Documentation for this module may be created at Module:Context-link/doc

-- <nowiki>
-- This module implements context-link templates.
local p = {}
local getArgs = require('Dev:Arguments').getArgs

-- Helper functions

local function findnamespace(link)
    local namespace = link:match('^(.-):')

    if namespace then
        local namespaces = mw.site.namespaces[namespace]
        if namespaces then
            return namespaces.id
        end
    end

    return 0
end
 
local function linkformat(link, display)
    local namespace = findnamespace(link, false)
    local colon

    if namespace == 6 or namespace == 14 then
        colon = ':'
    else
        colon = ''
    end
 
    -- Find the display value.
    if not display then
        local page, section = link:match('^(.-)#(.*)$')
        if page then
            display = page .. ' § ' .. section
        end
    end
 
    -- Assemble the link.
    if display then
        return string.format('[[%s%s|%s]]', colon, link, display)
    else
        return string.format('[[%s%s]]', colon, link)
    end
end

local function build(desc, links, options)
    local linktext
    
    if next(links) == nil then
        linktext = '...'
    else
        linktext = table.concat(links, ', ', 1, #links - 1)
    
        if #links > 1 then
            linktext = linktext .. ', or '
        end
        linktext = linktext .. links[#links]
    end

    local container = mw.html.create('div')
        :addClass('context-link')
        :addClass(options.extraclasses)
        :cssText(options.extrastyles)
        :wikitext(desc .. ' ' .. linktext)

    return tostring(container)
end

-- Produces standard context-link text.
function p.contextlink(frame)
    local args = getArgs(frame)
    local desc = args.desc or 'For another page, see'
    local links = {}
    for i, link in ipairs(args) do
        local display = args['t' .. i]
        table.insert(links, linkformat(link, display))
    end

    local options = {}
    options.extraclasses = args.class
    options.extrastyles = args.style
    return build(desc, links, options)
end

return p
-- </nowiki>