Module:Link if exists/sandbox
Appearance
| This is the module sandbox page for Module:Link if exists (diff). See also the companion subpage for test cases (run). |
| This module is rated as ready for general use. It has reached a mature state, is considered relatively stable and bug-free, and may be used wherever appropriate. It can be mentioned on help pages and other Wikipedia resources as an option for new users. To minimise server load and avoid disruptive output, improvements should be developed through sandbox testing rather than repeated trial-and-error editing. |
| This Lua module is used on approximately 292,000 pages. To avoid major disruption and server load, any changes should be tested in the module's /sandbox or /testcases subpages, or in your own module sandbox. The tested changes can be added to this page in a single edit. Consider discussing changes on the talk page before implementing them. |
Implements {{Link if exists}}.
Usage
[edit]{{#invoke:Link if exists|main}}
Arguments
[edit]- 1
- title of page to link to
- 2
- text to display
- prefix
- prepend this string to title
- nsp
- namespace for title, does not display
- color
- Color of text if no link is found
- hide_display
- If page does not exist, do not display anything
require('strict')
local p = {}
local function titleExistsUnprotected(titleObject)
return titleObject.exists
end
-- test for title existing
-- if we get an error accessing titleObject.exists, assume it doesn't exist
local function titleExists(titleObject)
local success, exists = pcall(titleExistsUnprotected, titleObject)
return success and exists
end
function p._main(args)
local title = args[1]
if not title then
return title
end
local display = args[2] or title
title = args.prefix and args.prefix..':'..title or title
local titleObject = mw.title.new(title, args.nsp)
local result = ''
if titleObject and titleExists(titleObject) then
-- use prefix only if args[2] is empty/false
display = args[2] or title
result = result..'[['
result = result..(titleObject.namespace ~= 0 and ':' or '')
result = result..(titleObject.fullText ~= display and titleObject.fullText..'|' or '')
result = result..display..']]'
elseif not args.hide_display then
result = result..(args.color and '<span style="color:'..args.color..'">' or '')
result = result..display
result = result..(args.color and '</span>' or '')
end
return result
end
function p.main(frame)
local getArgs = require('Module:Arguments').getArgs
local args = getArgs(frame)
return p._main(args) or ""
end
return p