• {{#invoke:template|example|tl|a|b|c=2}} → {{tl|a|b|c=2}}
  • {{#invoke:template|example|subst:tl|a|b|c=2}} → {{subst:tl|a|b|c=2}}
  • {{#invoke:template|example|safesubst:tl|a|b|c=2}} → {{safesubst:tl|a|b|c=2}}

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({ '|<tt>', name, '=', value, '</tt>' }) )
        elseif name ~= 1 then
            table.insert( result, table.concat({ '|<tt>', value, '</tt>' }) )
        end
    end
    
    return table.concat({ '{{', page, table.concat( result ), '}}' })
end

return template