Lua

CodeDiscussionEditHistoryLinksLink count Subpages:DocumentationTestsResultsSandboxLive code All modules

Code for {{Smartlink}}

Code

--[[
  __  __           _       _        ____                       _   _ _       _    
 |  \/  | ___   __| |_   _| | ___ _/ ___| _ __ ___   __ _ _ __| |_| (_)_ __ | | __
 | |\/| |/ _ \ / _` | | | | |/ _ (_)___ \| '_ ` _ \ / _` | '__| __| | | '_ \| |/ /
 | |  | | (_) | (_| | |_| | |  __/_ ___) | | | | | | (_| | |  | |_| | | | | |   < 
 |_|  |_|\___/ \__,_|\__,_|_|\___(_)____/|_| |_| |_|\__,_|_|   \__|_|_|_| |_|_|\_\
                                                                                  
 Authors and maintainers:
* User:Jarekt - original version
]]



--[[
This function is the core part of the Smartlink template. 
 
Usage from a template:
{{#invoke:Smartlink|Smartlink|1=|2= }}
 
Parameters:
  frame.args[1] - base page name
  frame.args[2] - desired language (often user's native language)

 Error Handling:

]]
local p = {}
function p.Smartlink(frame) 

	-- get base page and language fallback list
	local base = frame.args[1]
	if not mw.title.new(base) then
		-- missing, empty/whitespace-only or invalid title
		return ''
	end
	local lang = frame.args[2]
	if not lang or not mw.language.isSupportedLanguage(lang) then
		lang = frame:callParserFunction( "int", "lang" )           -- get user's chosen language 
	end
	local langList = mw.language.getFallbacksFor(lang)
	table.insert(langList,1,lang)

	-- find base template language subpage
	local page = nil
	for _, language in ipairs(langList) do
		if mw.title.new(base .. '/' .. language).exists then
			page =  base .. '/' .. language -- returns only the page
			return page
		end
	end
	return base
end

return p