Jump to content

Module:Lang if different

From Meta, a Wikimedia project coordination wiki
Module documentation
local p = {}

require 'strict'
local getArgs = require('Module:Arguments').getArgs

function p.main(frame)
	local args = getArgs(frame, { trim = false })
	-- language of the transcluded page
	local transcludedlang = args[1]
	-- language of the transcluding page
	local pagelang = mw.getCurrentFrame():preprocess('{{safesubst:' .. 'PAGELANGUAGE}}')
	local content = args[2]
	if transcludedlang == pagelang then
		-- translated, all well
		return content
	elseif content:match('^%s*<%a+ lang="[%a%-]+" dir="[rl]t[lr]"') then
		-- already has markup, no need for yet another one
		-- (very basic pattern, should match the Translate markup but may miss others)
		return content
	else
		local transcludedlangObj = mw.language.new(transcludedlang)
		local wrapper = mw.html.create(args['tag'])
		wrapper
			:attr('lang', transcludedlangObj:toBcp47Code())
			:attr('dir', transcludedlangObj:getDir())
			:wikitext(args['tag'] == 'div' and ('\n' .. content .. '\n') or content)
		return tostring(wrapper)
	end
end

return p