Module:Template

From Open Educational Resources
Revision as of 18:11, 7 October 2016 by Oeradmin (talk | contribs) (1 revision imported)
(diff) ← Older revision | Latest revision (diff) | Newer revision β†’ (diff)
Jump to navigation Jump to search

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

local template = {}

function template.page(frame)
    local title, subst = frame.args[1] or frame:getParent().args[1] or ''
    
    -- whether title is subst:page, safesubst:page, or page
    title = mw.ustring.gsub( title, '^%s*(s?a?f?e?subst):', function(what)
        if what == 'subst' or what == 'safesubst' then subst = what; return '' end
    end, 1 )
    
    local success, page = pcall(function(title) return mw.title.new( title, 10 ) end, title or '' )
    
    if not success or not page then return '' end
    if page.interwiki ~= "" then title = mw.ustring.sub( title, page.interwiki:len()+2 ) end
    if page.fragment ~= "" then title = mw.ustring:sub( title, 1, -page.fragment:len()-2 ) end
    if subst then subst = table.concat({ '[[Help:Templates#Substitution|', subst, ']]:' }) end
    
    return table.concat({ subst or '', '[[:', page.fullText, '|', title, ']]'})
end

function template.example(frame)
    local args, page, result = frame.args[1] and frame.args or frame:getParent().args, template.page(frame), {}
    
    if page == '' then
        return ''
    end
    
    for name, value in pairs( args ) do
        if type( name ) == 'string' then
            table.insert( result, table.concat({ '&#124;<tt>', name, '&#61;', value, '</tt>' }) )
        elseif name ~= 1 then
            table.insert( result, table.concat({ '&#124;<tt>', value, '</tt>' }) )
        end
    end
    
    return table.concat({ '{{', page, table.concat( result ), '}}' })
end

return template