跳转到内容

模組:Unsubst

維基詞典,自由的多語言詞典

此模塊可防止模板和模塊被錯誤替換。

用法

[编辑]

首先,將以下內容放在模塊中entry_point函數的開頭:

if mw.isSubsting() then
	return require('Module:unsubst').unsubst_template("entry_point")
end

其中"entry_point"應該替換為函數名。接下來,編輯模板:

{{safesubst:<noinclude/>#invoke:...|entry_point|...}}

<noinclude/>是可選的。模板將替換為其被嵌入的形式。

如果要保護模塊本身而不是模板,請在函數開始處添加:

if mw.isSubsting() then
	return require('Module:unsubst').unsubst_module("entry_point")
end

直接在模板中使用

[编辑]

您可以將模板代碼包裹在如下代码中:

{{safesubst:#invoke:unsubst|me|=
...
}}

結果同上述unsubst_template,另外還會生成對Module:Unsubst的嵌入。此外,它还可以防止模板被複製粘貼到非模板頁面。


-- Cannot unsubst if not currently being substed.

if not mw.isSubsting() then
	local frame_title = mw.getCurrentFrame():getTitle()

	-- If another module is calling this one, throw an error.
	if frame_title ~= "Module:unsubst" and frame_title ~= "Module:Unsubst" then
		error(("[[%s]] should not require [[Module:unsubst]] unless mw.isSubsting() returns true"):format(frame_title))
	end

	-- Otherwise, enable {{#invoke:unsubst|me|...}}.
	local export = {}

	local process_params = require("Module:parameters").process

	function export.me(frame)
		return process_params(frame.args, {
			[""] = true
		})[""]
	end

	return export
end

local m_pages = require("Module:pages")
local m_template_parser = require("Module:template parser")

local build_template = m_template_parser.buildTemplate
local concat = table.concat
local is_internal_title = m_pages.is_internal_title
local new_title = mw.title.new

local function get_title(frame)
	local title = new_title(frame:getTitle())
	return is_internal_title(title) and title or
		-- This shouldn't happen.
		error("frame returned an invalid title")
end

local function serialize(title, args)
	return "{{" .. concat(build_template(title, args), "|") .. "}}"
end

local mt = {}

if m_pages.is_transcluded() then
	local get_template_invocation_name = m_template_parser.getTemplateInvocationName

	function mt:__index(entry_point)
		return function(frame)
			frame = frame:getParent()
			return serialize(get_template_invocation_name(get_title(frame)), frame.args)
		end
	end
else
	function mt:__index(entry_point)
		return function(frame)
			local title = get_title(frame)
			return title.namespace == 828 and
				(serialize(("safesubst:<noinclude/>#invoke:%s|%s"):format(title.text, entry_point), frame.args)) or
				-- This shouldn't happen.
				error(("[[Module:unsubst]] cannot work if the current frame is not in the %s namespace, because the #invoke magic word requires it"):format(mw.site.namespaces[828].canonicalName))
		end
	end
end

return setmetatable({}, mt)