יחידה:תבנית חוזרת

ניתן ליצור תיעוד על היחידה הזאת בדף יחידה:תבנית חוזרת/תיעוד

local p = {}

function p.parse( frame )
	local template = frame.args['תבנית']
	local i = 0
	local req_params = {}
	-- extract parameters from templat
	while i~=nil do
		i = mw.ustring.find( template, '\{\{\{', i )
		if i ~= nil then
			start_ind = i+3
			i = mw.ustring.find( template, '\}\}\}', i )
			param_name = mw.ustring.sub( template, start_ind, i+2 )
			req_params[param_name] = 1
		end
	end
	
	-- expand argumetns using the template
	i=1
	local found = true
	local segments = {}
	local pFrame = frame:getParent()
	while found do
		local curr_template = template
		found = true
		for k,v in pairs(req_params) do
			cur_k = mw.ustring.gsub( k, 'X}}}', tostring(i), 1 )
			if pFrame.args[cur_k]  then 
				local val = pFrame.args[cur_k]
				local param_name = '\{\{\{'..k
				local start_ind = mw.ustring.find( curr_template, param_name )
				curr_template = mw.ustring.sub( curr_template, 0, start_ind-1) .. val .. mw.ustring.sub( curr_template, start_ind+mw.ustring.len( param_name ))
			elseif k=='?X}}}' then
					curr_template = mw.ustring.gsub( curr_template, '{{{%?X}}}', tostring(i)  )
			else
				found = false
				break
			end
		end
		if  found then
			segments[i] = curr_template
		end
      	i=i+1
    end
    return table.concat( segments, '\n' )
end

function p.invoker( frame )
	local res = {}
	local template = frame.args['תבנית']
	local templateParams = {}
	for k, v in pairs(frame.args) do
		if k~='תבנית' then
			templateParams[k] = v
		end
	end
	
	local callerParams = frame:getParent().args
	local i=0
	local maxI = 10
	while i<maxI do
		mw.logObject('Extracting params ' .. i)
		local currentArgs = {}
		for k, v in pairs(templateParams) do
			if i==0 then
				if callerParams[v] then
					currentArgs[k] = callerParams[v]
				end
			else
				if callerParams[v..i] then
					currentArgs[k] = callerParams[v..i]
				end
			end
		end
		mw.logObject('current args')
		mw.logObject(currentArgs)
		if #currentArgs == 0 and i>1 then
			i = maxI
		else
			table.insert(res, frame:expandTemplate{ title = template, args = currentArgs })
			if i==0 then
				i=2
			else
				i=i+1
			end
		end
	end
	return table.concat(res, '\n')
end

p['חזרה'] = p.parse
p['קריאה'] = p.invoker
return p