模块:If in page
| 警告 | 此模块被引用于约728,000个页面,占全部页面的15%。 为了避免造成大规模的影响,所有对此模块的编辑应先于沙盒或测试样例上测试。 测试后无误的版本可以一次性地加入此模块中,但是修改前请务必于讨论页发起讨论。 模板引用数量会自动更新。 |
注意事项[编辑]
此模块的内容已臻稳定,可正常使用于各处而不会出现错误。您现在可在分类和其他维基百科资源中提及此模块来帮助新用户学习。
为了降低服务器负载和错误输出,修改此模块前应先进行沙盒测试,而不是重复的试错性编辑。
简介[编辑]
此模板可用来侦测和匹配页面中是否有指定的mw.ustring模型,并输出为自定义结果。
参数及使用方法[编辑]
{{If in page|模型|存在時的輸出值|不存在時的返回值|page=|subst=}}{{#invoke:If in page|main|模型|存在時的輸出值|不存在時地返回值|page=|subst=}}
示例[编辑]
- 侦测和匹配当前页面中是否存在模型,并输出自定义结果:
{{If in page|模型|存在時輸出的結果|不存在時輸出的結果}}- 侦测和匹配指定页面中是否存在模型,并输出自定义结果:
{{If in page|模型|存在時輸出的結果|不存在時輸出的結果|page=頁面}}
参数资料[编辑]
<templatedata> { "format": "inline", "params": { "1": { "label": "模型", "description": "一个能被mw.ustring.match有效侦测和匹配的模型。", "type": "content", "required": true }, "2": { "label": "存在值", "description": "可在页面中侦测到模型的输出值。", "type": "content", "suggested": true }, "3": { "label": "不在值", "description": "无法在页面中侦测到模型的输出值。", "type": "content", "suggested": true }, "page": { "label": "页面", "description": "在指定页面上侦测模型,而非在当前的页面。", "type": "wiki-page-name", "suggested": true }, "subst": { "label": "替换", "description": "If set, then value if present will have %n replaced with capture groups, see doc", "type": "boolean" } } } </templatedata>
local p = {}
local getArgs = require('Module:Arguments').getArgs
function p.match(args)
if not args["page"] then
args.page = mw.title.getCurrentTitle().fullText
end
local page = mw.title.new(args.page)
if not page then
return args["3"] or ""
end
local content = page:getContent()
if not content then
return args["3"] or ""
end
if mw.ustring.match(content, args["1"] or "") then
if args["subst"] then
local pattern = args["1"] or ""
if mw.ustring.sub(pattern, 1, 1) ~= "^" then
pattern = "^.-" .. pattern
end
if mw.ustring.sub(pattern, -1) ~= "$" then
pattern = pattern .. ".*$"
end
local out = mw.ustring.gsub(content, pattern, args["2"] or "")
return out
else
return args["2"] or ""
end
else
return args["3"] or ""
end
end
function p.main(frame)
local args = getArgs(frame)
return p.match(args)
end
return p