模块:Unsubst

求闻百科,共笔求闻

此模组是为了预防不应替换引用的模板利用替换引用导入参数(自我替换引用模板)。

用法

{{{{{|safesubst:}}}#invoke:Unsubst||$B=

 [ ... 模板的其餘內容 ... ]

}}

参数“$B”为不替换引用时的模板内容。除了$B外所有传入的参数皆视为是替换引用后的模板代码,参数__DATE__会自动转换成时间(Y年n月)。

有些模板有加上<noinclude>但未在结尾加上</noinclude>,此时必须补上。

范例

正常时模板应使用此格式:

{{ {{{|safesubst:}}}#invoke:Unsubst||參數1=值1|date=__DATE__ |$B=

 [ ... 模板的其餘內容 ... ]

}}<noinclude>
{{doc}}
</noinclude>
源代码 结果
模板链接:{{subst:example}} 模板链接:{{Example|參數1=值1|date=2024年4月}}
模板链接:{{subst:example|參數1=X}} 模板链接:{{Example|參數1=X|date=2024年4月}}
模板链接:{{subst:example|參數2=X}} 模板链接:{{Example|參數1=值1|參數2=X|date=2024年4月}}
模板链接:{{subst:example|date=模板链接:{{subst:[[#time:c|#time:c]]}}}} 模板链接:{{Example|參數1=值1|date=2024-04-28T14:34:14+00:00}}



上述文档内容嵌入自Module:Unsubst/doc编辑 | 历史
编者可以在本模块的沙盒创建 | 镜像和测试样例创建页面进行实验。
请将模块自身所属的分类添加在文档中。本模块的子页面
local p = {}

local specialParams = {
	['$N'] = 'template name', -- Deprecated, but keeping until it is removed from transcluding templates
	['$B'] = 'template content',
}

p[''] = function ( frame )
	if not frame:getParent() then
		error( '{{#invoke:Unsubst|}} makes no sense without a parent frame' )
	end
	if not frame.args['$B'] then
		error( '{{#invoke:Unsubst|}} requires parameter $B (template content)' )
	end
	
	if mw.isSubsting() then
		---- substing
		-- Combine passed args with passed defaults
		local args = {}
		for k, v in pairs( frame.args ) do
			if not specialParams[k] then
				if v == '__DATE__' then
					v = mw.getContentLanguage():formatDate( 'Y年n月' )
				end
				args[k] = v
			end
		end
		for k, v in pairs( frame:getParent().args ) do
			args[k] = v
		end

		-- Build an equivalent template invocation
		-- First, find the title to use
		local titleobj = mw.title.new(frame:getParent():getTitle())
		local title
		if titleobj.namespace == 10 then -- NS_TEMPLATE
			title = titleobj.text
		elseif titleobj.namespace == 0 then -- NS_MAIN
			title = ':' .. titleobj.text
		else
			title = titleobj.prefixedText
		end

		-- Build the invocation body with numbered args first, then named
		local ret = '{{' .. title
		for k, v in ipairs( args ) do
			if string.find( v, '=', 1, true ) then
				-- likely something like 1=foo=bar, we need to do it as a named arg
				break
			end
			ret = ret .. '|' .. v
			args[k] = nil
		end
		for k, v in pairs( args ) do
			ret = ret .. '|' .. k .. '=' .. v
		end
		
		return ret .. '}}'
	else
		---- Not substing
		-- Just return the "body"
		return frame.args['$B'] .. (frame.args['$N'] and frame:getParent():getTitle() == mw.title.getCurrentTitle().prefixedText and '[[Category:使用$N的Module:Unsubst调用]]' or '')
	end
end

return p