Jump to content

Module:Template parameter value

Permanently protected module
From Wikipedia, the free encyclopedia

localp={}localPrepareText=require("Module:Wikitext Parsing").PrepareTextlocalfunctiongetTitle(title)localsuccess,titleObj=pcall(mw.title.new,title)ifsuccessthenreturntitleObjelsereturnnilendend--string.gmatch will check the largest block it can without re-scanning whats inside, but we need whats insidelocalfunctionmatchAllTemplates(str)localmatches={}fortemplateinstring.gmatch(str,"{%b{}}")dotable.insert(matches,template)localinnerContent=string.sub(template,3,-3)for_,subtemplateinnext,matchAllTemplates(innerContent)dotable.insert(matches,subtemplate)endendreturnmatchesend--Forked version of getParameters from [[Module:Transcluder]] with extra features removedlocalfunctionescapeString(str)returnstring.gsub(str,'[%^%$%(%)%.%[%]%*%+%-%?%%]','%%%0')endlocalfunctiongetParameters(template)localparameters,parameterOrder={},{}localparams=string.match(template,'{{[^|}]-|(.*)}}')ifparamsthenlocalcount=0-- Temporarily replace pipes in subtemplates and wikilinks to avoid chaosforsubtemplateinstring.gmatch(params,'{%b{}}')doparams=string.gsub(params,escapeString(subtemplate),string.gsub(subtemplate,".",{["%"]="%%",["|"]="@@:@@",["="]="@@_@@"}))endforwikilinkinstring.gmatch(params,'%[%b[]%]')doparams=string.gsub(params,escapeString(wikilink),string.gsub(wikilink,".",{["%"]="%%",["|"]="@@:@@",["="]="@@_@@"}))endforparameterinmw.text.gsplit(params,'|')dolocalparts=mw.text.split(parameter,'=')localkey=mw.text.trim(parts[1])localvalueif#parts==1thenvalue=keycount=count+1key=tostring(count)elsevalue=mw.text.trim(table.concat(parts,'=',2))endvalue=string.gsub(string.gsub(value,'@@:@@','|'),'@@_@@','=')key=string.gsub(string.gsub(key,'@@:@@','|'),'@@_@@','=')table.insert(parameterOrder,key)parameters[key]=valueendendreturnparameters,parameterOrderend-- Returns a table containing parameters and a table with the order in which each of their values were found.-- Since this considers all subtemplates, a single parameter is expected to have multiple values.-- E.g. {{ABC|X={{DEF|X=Value|Y=Other value}}{{ABC|X=Yes}}|Y=P}}-- Would return {X={"{{DEF|X=Value|Y=Other value}}", "Value", "Yes"}, Y={"Other value", "P"}}localfunctiongetAllParameters(template,ignore_blank,only_subtemplates)localparameterTree=setmetatable({},{__index=function(self,key)rawset(self,key,{})returnrawget(self,key)end})localparams,paramOrder=getParameters(template)for_,keyinipairs(paramOrder)dolocalvalue=params[key]ifnotignore_blankorvalue~=""thenifnotonly_subtemplatesthentable.insert(parameterTree[key],value)--Insert the initial value into the treeendforsubtemplateinstring.gmatch(value,"{%b{}}")do--And now check for subvalueslocalsubparams=getAllParameters(subtemplate,ignore_blank)forsubkey,subsetinnext,subparamsdofor_,subvalueinipairs(subset)dotable.insert(parameterTree[subkey],subvalue)--And add any we find to our treeendendendendendreturnparameterTreeend--Module entry point. Returns a success boolean and either the target template or why it failedfunctionp.getTemplate(page,templates,options)ifnottemplatesthen--Required parametersreturnfalse,"Missing required parameter 'templates'"endoptions=optionsor{}localtemplate_index=tonumber(options.template_index)or1localtreat_as_regex=options.treat_as_regexorfalseiftype(templates)=="string"then-- TODO: Find a good way to allow specifying multiple templates via template invocation-- (Modules can just provide a table so no concerns there)-- Comma splitting is a bad idea (lots of templates have a comma in their name)templates={templates}endlocaltitle=getTitle(page)iftitle==nilthenreturnfalse,"Requested title doesn't exist"endlocalcontent=PrepareText(title:getContent()or"")localfoundTemplates=0localfoundTemplatefor_,templateinnext,matchAllTemplates(content)dofor_,wantedTemplateinpairs(templates)doifnottreat_as_regexthenwantedTemplate=escapeString(wantedTemplate)endlocalfirstLetter=string.sub(wantedTemplate,1,1)localfirstUpper,firstLower=firstLetter:upper(),firstLetter:lower()iffirstUpper~=firstLowerthenwantedTemplate="["..firstUpper..firstLower.."]"..string.sub(wantedTemplate,2)endifstring.match(template,"^{{%s*"..wantedTemplate.."%s*[|}]")thenfoundTemplate=templatefoundTemplates=foundTemplates+1iffoundTemplates==template_indexthen--Found our wanted templatereturntrue,foundTemplateendendendendiffoundTemplates>0andtemplate_index==-1thenreturntrue,foundTemplateendreturnfalse,"No valid template found"end--Module entry point. Returns a success boolean and either the target parameter's value or why it failedfunctionp.getParameter(page,templates,parameter,options)ifnot(templatesandparameter)then--Required parametersreturnfalse,"Missing required parameters 'templates' and 'parameter'"endparameter=tostring(parameter)--Force consistencyoptions=optionsor{}localsuccess,text=p.getTemplate(page,templates,options)ifnotsuccessthenreturnsuccess,textelselocalparameter_index=tonumber(options.parameter_index)or1localignore_subtemplates=options.ignore_subtemplatesorfalselocalonly_subtemplates=options.only_subtemplatesorfalselocalignore_blank=options.ignore_blankorfalselocalvalueifignore_subtemplatesthenvalue=getParameters(text)[parameter]or""elselocalparams=getAllParameters(text,ignore_blank,only_subtemplates)value=params[parameter][parameter_index]or""endvalue=string.gsub(value,"</?%a*include%a*>","")value=mw.text.trim(value)--technically wrong in some cases but not a big issuereturntrue,mw.text.decode(value)--decode due to PrepareTextendend--Template entry point. Returns either "yes" or nothing depending on if the wanted template is found--Will return error text if no template is providedfunctionp.hasTemplate(frame)localargs=require('Module:Arguments').getArgs(frame)localyesno=require("Module:Yesno")localpage=args[1]orargs.pagelocaltemplate=args[2]orargs.templatelocaltemplate_index=tonumber(args[3]orargs.N)or1ifnottemplateortemplate==""thenreturn'<span class="error">No template provided for hasTemplate</span>'endlocalfollow=yesno(args.follow)orfalseiffollowthenpage=require("Module:Redirect").luaMain(page)endlocaloptions={template_index=template_index,treat_as_regex=yesno(args.treat_as_regex)orfalse,}localsuccess,_=p.getTemplate(page,template,options)returnsuccessand"yes"or""end--Template entry point for getParameter. Returns an empty string upon failurefunctionp.main(frame)localargs=require('Module:Arguments').getArgs(frame,{wrappers='Template:Template parameter value'})localyesno=require("Module:Yesno")localoptions={template_index=args[3]orargs.template_index,parameter_index=args[5]orargs.parameter_index,ignore_subtemplates=yesno(args.ignore_subtemplatesorargs.ist)orfalse,only_subtemplates=yesno(args.only_subtemplates)orfalse,ignore_blank=yesno(args.ignore_blank)orfalse,treat_as_regex=yesno(args.treat_as_regex)orfalse,}localpage=args[1]orargs.pagelocaltemplate=args[2]orargs.templatelocalparameter=args[4]orargs.parameterlocalsuccess,result=p.getParameter(page,template,parameter,options)ifnotsuccessthenreturn""elseifargs.dontprocessthenreturnresultelsereturnframe:preprocess(result)endendend--Backwards compatabilityp.getValue=p.getParameter--Potentially useful module entry pointsp.matchAllTemplates=matchAllTemplatesp.getParameters=getParametersp.getAllParameters=getAllParametersreturnp
close