Module:Link

来自滚动的天空Wiki
文档图示 模块文档[查看] [编辑] [查看历史] [清除缓存]

本模块用于给文本添加链接,或者处理含有链接的文本。

给文本添加链接[编辑源代码]

当文本已有内链时不再创建内链。此外如果文本以英文单引号(')开头,则也不会创建内链(文本不会包括这个单引号)。请看示例:

代码 结果
{{#invoke:link|main|微芯片}} 微芯片
{{#invoke:link|main|关卡[[微芯片]]}} 关卡微芯片
{{#invoke:link|main|'微芯片}} 微芯片

除去所有的链接[编辑源代码]

将文本中所有的链接除去,只留下显示文字。例如:

代码 结果
{{#invoke:link|reduce|这是一个[[页面]],以及[[页面名称|显示文字]]。}} 这是一个页面,以及显示文字。

提取所有的链接[编辑源代码]

将文本中所有的链接页面返回,并组成一个列表。可以通过sep参数指定分隔符,默认为一个顿号。返回的结果常用于储存在Cargo数据中。

代码 结果
{{#invoke:link|extract|这是一个[[页面]]、[[页面名称|显示文字]]、[[:Category:分类]]。}} 页面、页面名称、Category:分类
{{#invoke:link|extract|这是一个[[页面]]、[[页面名称|显示文字]]、[[:Category:分类]]。|sep=/}} 页面/页面名称/Category:分类
上述文档内容嵌入自Module:Link/doc编辑 | 历史
编者可以在本模块的沙盒创建 | 镜像和测试样例创建页面进行实验。
请将模块自身所属的分类添加在文档中。本模块的子页面
local p = {}

function p._main(text, display)
	-- text不会被自动除去空格
	if text == "" or (not text) then
		return display or ""
	elseif text:sub(1,1) == "'" then
		return display and text:sub(2)..'|'..display or text:sub(2)
	elseif text:find '%[%[' or text:find '%]%]' then
		return display and text..'|'..display or text
	elseif display then
		return '[[' .. text .. '|' .. display .. ']]'
	else
		return '[[' .. text .. ']]'
	end
end

function p.main(f)
	-- 用于模块调用
	local text = f.args[1]
	local display = f.args[2]
	local a,b
	a,b = pcall(mw.text.trim,text)
	if a then text=b else text=nil end
	a,b = pcall(mw.text.trim,display)
	if a then display=b else display=nil end
	return p._main(text,display)
end

function p._reduce(text)
	-- 用于移除所有的内链
	return (text
		:gsub('%[%[(.-)]]',function (s)
			s = s:sub(1,1)==':' and s:sub(2,-1) or s
			local pipeindex1,pipeindex2 = s:find('|',0,true)
			local text = pipeindex2 and s:sub(pipeindex2+1,-1) or s
			return text
		end))
end

function p.reduce(f)
	local text = f.args[1]
	return p._reduce(text)
end

function p._extract(text)
	-- 用于提取出所有被链接的内容
	local result = {}
	for s in text:gmatch '%[%[(.-)]]' do
		-- 尝试检测用管道符号分开的两个部分
		s = s:sub(1,1)==':' and s:sub(2,-1) or s
		local pipeindex1, pipeindex2 = s:find('|', 0, true)
		local page = pipeindex1 and s:sub(1, pipeindex1-1) or s
		result[#result+1] = page
	end
	return result
end

function p.extract(f)
	local args = f.args
	local text = args[1]
	local index = tonumber(args.index)
	local sep = args.sep or '、'
	local pages = p._extract(text)
	if index then
		return pages[index] or (#pages>0 and '' or text)
	else
		return #pages>0 and table.concat(pages, sep) or text
	end
end

return p