Help:Advanced templates: Difference between revisions

From Meta, a Wikimedia project coordination wiki
Content deleted Content added
return to earlier version; 2022-06
Tag: Manual revert
 
(332 intermediate revisions by 69 users not shown)
Line 1: Line 1:
{{H:h}}[[Category:Editor handbook]]
{{h:hns}}
This page is an extension of '''[[Help:Template]]'''.


==A template name or a parameter value depending on a parameter or variable==


This page covers '''advanced template techniques''', particularly, the use of variable template names, and parameter names in templates. Readers, should first be thoroughly familiar with the ''standard template techniques'', found in [[Help:Template]]. Some of the techniques described below, may be outdated or of limited use; for example, [[mw:Help:Extension:ParserFunctions|ParserFunctions]] and [[mw:Extension:Scribunto/Lua reference manual|Lua]], may be more convenient alternatives to using some of the branching techniques discussed.
A template name and a parameter value can both depend on a parameter or variable:
*<nowiki>{{tt|t|efg}}</nowiki> using {{ut|Tt}} and {{ut|T}}, produces "{{tt|t|efg}}"
*<nowiki>{{{{NAMESPACE}}}}</nowiki>, using [[Template:Help]], gives "{{{{NAMESPACE}}}}"
*see [[Template:Histogram]]


In general, these techniques rely on the ''recursive'' (inside-out) processing of templates. When a template is ''[[Help:Expansion|expanded]]'' (processed), it translates the given template code into string values. These are often sent directly to the web browser for display, however, they can be treated as code themselves. For instance, by enclosing the text strings in double-curly-brackets ( {{}} ), they can be ''reprocessed'' as template names or variable names; thus, producing different results as the string values are changed.
This allows [[w:en:Conditional_branching#Choice|branching]] depending on variables and parameters. However, since no conditions such as {{{1}}}<a can be evaluated, and no substrings can be extracted from strings, etc., this works best if each parameter and variable has only a limited number of possible values. For example <nowiki>{{</nowiki>CURRENTDAYNAME}} has only seven possible values, so all cases can be handled with seven templates; if there are really only two cases, five of the seven could be redirects. On the other hand , <nowiki>{{</nowiki>CURRENTTIME}} has 1440 possible values, so it is almost impossible to use that variable for branching.


'''Notes:'''
Having multiple parameters, which each can have only few values, is more flexible than having the same total number of possibilities in a single parameter.
*This document refers to features that are currently, only available in the [[mw:Mediawiki software]], starting with version 1.6 and later.
*The term "variable" has two uses in this document:
::;Variable (n.): refers to [[mw:Help:Magic_words#Variables|a type of magic word]]——a ''system-based variable'' that can be accessed in the same manner as templates——thus, <nowiki>{{NAMESPACE}}</nowiki> will return the name of the current namespace, depending on the page.
::;Variable (adj. ''or'' adv.): used in a general sense to indicate that parts within the context may vary; hence, a ''variable template name'', states that the name of the template being called, can be changed, according to the parameters or variables.
*Using "subst:" with manual recursion, gives a step–wise replacement, useful for analyzing and explaining the working of templates calling other templates. For instance, compare <code><nowiki>{{{{tctc}} }}</nowiki></code> (discussed below) with <code><nowiki>{{{{subst:tctc}} }}</nowiki></code>, on a sandbox page. Although both produce the same ''visible'' result, the first will remain as the full code <code><nowiki>{{{{tctc}} }}</nowiki></code>, while the second will replace the inner template <code><nowiki>{{tctc}}</nowiki></code> with its value, leaving the code <code><nowiki>{{tc }}</nowiki></code>.


If a template depends on PAGENAME, then the many possible values need not be a problem: only the pagenames of the pages that call the template apply, and these can be limited.


== Variable templates ==
Branching according to {{{1}}}=a or {{{1}}}&ne;a ''is'' possible, see the section [[#A parameter name depending on a parameter]].


<section begin=vartemp />In some cases, it may be useful for a template to call different templates depending on a variable or a passed parameter. This allows a type of [[w:en:Conditional_branching#Choice|branching]] that can be simpler than with [[mw:Help:Extension:ParserFunctions|ParserFunctions]], though they are generally less versatile.<section end=vartemp /><!--section tags for demo in [[Help:Template#Labeled section transclusion]]-->
==Examples of pages that call a template with a name depending on a variable==
*NAMESPACE
**[[Template:H:h]] and [[Template:H:f]] (see edit pages, [[Help:MediaWiki_help_policy#Keeping_project-specific_material_separate|MediaWiki help policy]], and [http://meta.wikimedia.org/w/index.php?title=Special:Allpages/h&namespace=10 list])
**[[Template:Nsn]] - namespace number (see also below)
**[[Template:Namespace of associated page]] - for use on talk pages; applied in [[Template:Lap]]
**[[Template:Name of talk namespace]]
**[[de:MediaWiki:Newarticletext]] and [[de:MediaWiki:Noarticletext]] (see edit pages and [http://de.wikipedia.org/w/index.php?title=Spezial:Allpages/MediaWiki&namespace=10 list])
*PAGENAME
**[[Template:H:1]] - for project-specific content on selected help pages, see [[Help:MediaWiki_help_policy#Template:h:1|MediaWiki help policy]]
**[[w:en:Template:H:f]] - for project-specific content on all help pages of the English Wikipedia (requires a blank template on all pages that no not have this content)


'''Examples:'''
==Arrays with a template for each element==
<!-- experimenting with different formats
{| class="wikitable" style="width:75%;border:none"
|+Using a variable to choose a template - <nowiki>{{ {{NAMESPACE}} }}</nowiki>
|-
!This...
!Produces this
|-
|<nowiki>{{NAMESPACE}}</nowiki>
|{{NAMESPACE}}
|-
|<nowiki>{{ {{NAMESPACE}} }}</nowiki> is equivalent to <nowiki>{{</nowiki> {{NAMESPACE}} <nowiki>}}</nowiki>
|{{ {{NAMESPACE}} }}
|} -->
;''Using a variable to choose a template'' - <code><nowiki>{{ {{NAMESPACE}}}}</nowiki></code>:The [[help:Magic words|magic word]] <nowiki>{{NAMESPACE}}</nowiki> returns the current namespace, like so: <nowiki>{{NAMESPACE}}</nowiki> = ''{{NAMESPACE}}''. The outer brackets then process this result as a template in its own right - in this case [[Template:Help]] - which produces ''{{ {{NAMESPACE}}}}''.
;''Using a template to choose a template'' - <code><nowiki>{{ {{tctc}}}}</nowiki></code>:the template {{tl|Tctc}} contains the text "tc". This text is processed by the outer brackets as [[Template:tc]] which contains the word "{{ {{tctc}}}}".


The extra spaces in the above examples are needed: without them, the pair of inner three braces is taken as those for a parameter. On the page itself it just shows as plain text: {{((}}{{((}}{{NAMESPACE}}{{))}}{{))}}.<!-- To prevent syntaxhighlighting errors. Realistically {{{{NAMESPACE}}}} will be rendered as plain text. -->
A set of templates can form a kind of [[w:en:associative array|associative array]]. A 1D [[w:en:array|array]] has elements which are templates with names of the form ''array-name'' ''index'', a 2D array ([[w:en:Matrix (mathematics)|matrix]]) has elements which are templates with names of the form ''array-name'' ''index1'' ''separator'' ''index2''. The indexes can be any text.


;''Using a parameter to choose a template'' - <code><nowiki>{{{{{2}}}x|{{{1}}}}}</nowiki></code>:The second parameter passed becomes part of the template name to which the first parameter is passed. In this case <code>{{tlx|2x|{{{1}}}}}</code> would produce <code><nowiki>{{{1}}}{{{1}}}</nowiki></code>, <code>{{tlx|3x|{{{1}}}}}</code> would produce <code><nowiki>{{{1}}}{{{1}}}{{{1}}}</nowiki></code>, and etc. [[Template:Hist5]] uses this technique repeatedly in {{tlx|hist5|X|4|7|3|2|9}} to produce the following 5 line histogram:
For example, on Meta there are templates with names of the form "Lang_name_-_''language referred to''_(''language used'' )" (in fact, the pattern is an example of a generalized form of the name pattern, with a text, here a closing parenthesis, after the second index) with codes used for the two languages; the contents of each template is the word for a language, expressed in the same or another language, e.g. [[Template:Lang name - de (fr)]] contains "Allemand", which is "German" in French. (See [http://meta.wikimedia.org/w/index.php?title=Special:Allpages/Lang_name&namespace=10 list]; for [[w:en:Main diagonal|diagonal elements]] such as [[Template:Lang name - de (de)]] there are, in addition, copies such as [[Template:Lang name - de]]). See also [[User:Suruena/i18n (en)|explanation page]].


<blockquote>{{hist5|X|4|7|3|2|9}}</blockquote>
In the case of a 2D array ''separator'' and the possible values of ''index1'' and ''index2'' should be chosen such that there is no ambiguity; no separator is needed if at least one index is of fixed length, or e.g. if the first index consists of letters and the second of digits. The software does not need to parse ''index1'' ''separator'' ''index2'', but for convenient human parsing a separator such as a blank space may be preferred in some cases where it is not strictly needed.


Using [[help:Parser function|parser functions]] and templates, including those which process strings (see [[Help:String functions]] and [[:Category:String manipulation templates]]), a template name can also depend in a more complicated way on parameters and/or variables.
Elements of a 1D array can e.g. be referred to inside a template with <nowiki>{{</nowiki>''array-name'' {{{''index''}}}}} using parameter ''index'', or similarly with a variable. Also a page can successively call each array element using <nowiki>{{</nowiki>''array-name'' ''index''}} with varying ''index''.


== Templates passed as parameters ==
In the case of a 2D array, a template may have a row index as parameter and produce a list based on that row of the matrix, or similarly for columns. See e.g. [[Template:List of Languages]].


Templates can be passed as parameters to other templates. This can mean either that the template is evaluated and the result is passed as a parameter or that the template name is passed and evaluated as part of the other template.
A disadvantage of having a template for each array element is that it is extremely cumbersome to copy a large array to another project, unless a bot is used, or a developer assists.


;''Passing a template result'' - <nowiki>{{3x|{{tc}}}}</nowiki>: [[Template:3x]] contains <nowiki>{{{1}}}{{{1}}}{{{1}}}</nowiki>. <nowiki>{{3x|{{tc}}}}</nowiki> first evaluates {{tl|tc}} (which yields {{tc}}), and passes that to template {{tl|3x}}, to give {{3x|{{tc}}}}.
An advantage is that the absence of a data value shows up as a link to a non-existing template, allowing an individual data value to be added easily. Depending on how fast the servers are, adding multiple values may be slower, sometimes much slower, than when fewer templates have to be edited.
;''Passing a template result recursively'' - <nowiki>{{3x|{{5x|{{tc}}}}}}</nowiki>: Just as above except {{tl|tc}} ({{tc}}) is first passed to {{tl|5x}} and the result of that is passed to {{tl|3x}}, to give {{3x|{{5x|{{tc}}}}}}.


<!-- hiding this temporarily while I sort it out - very confusing
Another example:
Thus, it is also possible to use a data array as a parameter of a template, e.g.,:
*See [[w:en:Template talk:Articlespace]]: the namespaces are the index values, the no-talk namespaces are the array values.
*See [[it:Discussioni template:TALKSPACE]]: the namespaces are the index values, the talk namespaces are the array values.


<nowiki>{{</nowiki>hist5a|x|t data}} using
==A 1D array contained in a template==


{{timcnl|hist5a}} and
In the following way an array can take the form of a template (an alternative for "P" is possible, but consistency is desirable):
*For all values of the index used, Template:P''value-of-index'' is defined, with the content {{{''value-of-index'' }}} (see [http://meta.wikimedia.org/w/index.php?title=Special:Allpages/p&namespace=10 list]). Where suitable, indexes of various arrays should be named the same, so that these templates can be reused.
*An array has the form of a template with the contents
**{{p{{{1}}}|''value-1-of-index'' =''value-of-array-element-1'' |''value-2-of-index'' =''value-of-array-element-2'' |..}}
*or if index values 1,2,3,.. are used, simply
**{{p{{{1}}}|''value-of-array-element-1'' |''value-of-array-element-2'' |..}}
*An array element is referred to as <nowiki>{{</nowiki>''template name'' |''index'' }}.


{{timc|t data}} gives:
Alternatively the parameter <nowiki>{{{</nowiki>1}}} is replaced by a variable, as in [[Template:Nsn]] (name space number). Since for every applicable value of the variable a template has to be created, this is mainly suitable for variables that do not take too many values, and also in the case that the template is only applied in cases where a suitable subset of values applies.


{{hist5a|x|t data}}
In the case of a parameter <nowiki>{{{1}}}</nowiki> there is no reason to choose the parameter names (before the "=", and in the tag in the corresponding template) differently from the corresponding index values (the template names without the "P"); even the empty string is a valid parameter name.
-->
;''Passing a template name'' - <code><nowiki>{{tto|t|V}}</nowiki></code>:'''[[Template:tto]]''' - <code><nowiki>{{{{{1}}}|a{{{2}}}b{{{2}}}c{{{2}}}d}}</nowiki></code> - takes the value '''V''' (passed as the second parameter) and produces ''aVbVcVd''. This value is then passed to '''[[template:t]]''' (which was passed by name as the first parameter), producing "{{tto|t|V}}".


In interpreting this sequence <code><nowiki>{{tto|t|V}}</nowiki></code>, the parser :
One has to decide whether a blank space or an underscore is used, they are not distinguished in template names, but they are in parameter names; the templates <nowiki>P{{NAMESPACE}}</nowiki>, and hence the arrays that call the, use a blank space, where applicable, see e.g. [[Template:PHelp talk]] (although <nowiki>{{ns:3}}</nowiki> gives {{ns:3}} with an underscore, it is anyway not possible to have a parameter name depend on a variable, see below). Capitalization has to be consistent for parameter names as well as inside template names, as a P comes in front.
# sees that <code><nowiki>{{tto|t|V}}</nowiki></code> is formally a valid template call, with :
#* template name = "tto"
#* parameter 1 = "t"
#*parameter 2 = "V"
# evaluates the current values both of the template name and of its parameter,
#* template = [[:template:tto]]
#* {{{1}}} := t
#* {{{2}}} := V
# gets the current value of the template content <code><nowiki>{{{{{1}}}|a{{{2}}}b{{{2}}}c{{{2}}}d}}</nowiki></code>
## (recursively) sees that <code><nowiki>{{{{{1}}}|a{{{2}}}b{{{2}}}c{{{2}}}d}}</nowiki></code> formally contains a valid template call, with :
##* template name = {{{1}}}
##* parameter 1 = a{{{2}}}b{{{2}}}c{{{2}}}d
## evaluates the current values both of the template name and of its parameter, in the context where {{{1}}} = b and {{{2}}} = V, giving :
##* template name = b
##* parameter 1 = aVbVcVd
## gets the current value of the template content <code><nowiki>start-{{{1}}}-end</nowiki></code>
##applies the template to its parameters, producing "{{tto|t|V}}".
# (recursively) returns the value.


== Variable parameter name ==
A disadvantage compared with the system mentioned above is that the absence of a data value shows up as {{{''index'' }}}, as opposed to presenting a link to fill in the value. Referring to a defined array element without the auxiliary Template:P''index'' being defined, a link to that template ''does'' show up, allowing this to be easily fixed.


A parameter name in a template can be the value of another parameter. This is useful if you want the behavior of a template to change based on the information that is provided to it.
'''Translations'''

One application is a template that contains translations of a particular term, where the indexes are the language codes.

'''Example 1:'''

[[Template:Book]] contains

*{{msg:Book}}

[[Template:Pfr]] contains {{msg:pfr}}, etc.

<nowiki>{{book|fr}}</nowiki> gives {{book|fr}}.

'''Example 2:'''

[[Template:Nsnp]] (namespace number, with parameter) contains

*{{msgnw:nsnp}}

[[Template:PUser]] contains {{msg:PUser}}, etc.

<nowiki>{{nsnp|namespace=User}}</nowiki> gives {{nsnp|namespace=User}}.

<nowiki>{{nsnp|{{NAMESPACE}}}}</nowiki> gives {{nsnp|namespace={{NAMESPACE}}}}.

Compare [[Template:Nsn]] (namespace number), which contains

*{{msgnw:nsn}}

<nowiki>{{nsn}}</nowiki> gives {{nsn}} (the same).

==A 2D array with each row (or column) contained in a template==

A collection of templates can be used as a 2D array: each row is contained in a template, and the template names consist of a common part (which can be considered the name of the 2D array) and a row index.

Thus an array element is referred to by <nowiki>{{</nowiki>''2D-array-name'' ''index1'' |''index2'' }}

'''Example: 2D array N'''

Template:N''language-code'' contains the word for various languages, expressed in one language.

[[Template:N de]] contains

*{{msgnw:n de}}

<nowiki>{{n de|fr}}</nowiki> gives {{n de|fr}}.

The choice of what is put together in one template (a row or a column of a given matrix) can either be based on whether <nowiki>{{n de|fr}}</nowiki> or <nowiki>{{n fr|de}}</nowiki> is a more natural notation for this word, or, as has been done here, on what is more practical in filling the templates with data.

==A 2D array contained in a single template==
A 2D array can be contained in a single template if a composite index of the form ''index1'' ''separator'' ''index2'' is used.

Thus an array element is referred to by <nowiki>{{</nowiki>''2D-array-name'' |''index1'' ''separator'' ''index2'' }}

The same remarks as above apply for the separator.

Example: [[Template:Ln]] contains
*{{msgnw:ln}}

<nowiki>{{ln|de fr}}</nowiki> gives {{ln|de fr}}.

==Arrays of higher dimensions==
An 3D array can have in each template a single element, a 1D array, a 2D array, or the whole 3D array; correspondingly an element is referred to in one of the folowing ways:
*<nowiki>{{</nowiki>''3D-array-name'' ''index1'' ''separator1'' ''index2'' ''separator2'' ''index3'' }}
*<nowiki>{{</nowiki>''3D-array-name'' ''index1'' ''separator'' ''index2'' |''index3'' }}
*<nowiki>{{</nowiki>''3D-array-name'' ''index1'' |''index2'' ''separator'' ''index3'' }}
*<nowiki>{{</nowiki>''3D-array-name'' |''index1'' ''separator1'' ''index2'' ''separator2'' ''index3'' }}

An example of a 4D array is at Commons, with elements of the form <nowiki>Template:Potd/{{CURRENTYEAR}}-{{CURRENTMONTH}}-{{CURRENTDAY}} ({{{lang}}})</nowiki>, each in a separate template, such as [[commons:Template:Potd/2005-06-2 (de)]]. Most of the templates on the project are in this array (see [http://commons.wikimedia.org/w/index.php?title=Special:Allpages&namespace=10 list]).

Correspondingly there is a 3D array of image names of the form <nowiki>Template:Potd/{{CURRENTYEAR}}-{{CURRENTMONTH}}-{{CURRENTDAY}}</nowiki> such as [[commons:Template:Potd/2005-06-2]] and a corresponding set of images of the form <nowiki>[[Image:{{Template:Potd/{{CURRENTYEAR}}-{{CURRENTMONTH}}-{{CURRENTDAY}}}}</nowiki>. The latter can also be considered a 3D array, but with the restriction that elements can only be accessed ''as such'' from the project itself (the elements can be accessed, and from Wikimedia projects be embedded, e.g. [[Image:Cataratas027.jpg|50px|]], but the key to them in terms of the indexes can only be accessed, as the link above shows, but not automatically used).

==Other ways of organizing arrays for easy access==

Sections and anchors can be used, if they are systematically named. This only allows separate viewing, not inserting array elements in other texts.

Examples:

*[[Help:Template names, variable names and parameters depending on a variable or parameter/Array demo using section linking#fr de]]
*Pages for each month with an overview of the 2D sub-array of the 4D array on Commons, together with the corresponding images, in combination with section linking, provide direct access to the overview of the 1D sub-array and the image for a given day, for today <nowiki>[[commons:Template:Potd/{{CURRENTYEAR}}-{{CURRENTMONTH}}#{{CURRENTDAY}}]]</nowiki> giving [[commons:Template:Potd/{{CURRENTYEAR}}-{{CURRENTMONTH}}#{{CURRENTDAY}}]].

==Naming conventions of array templates==
It is not obvious whether a singular or plural name should be used if a single template contains several data, but they are retrieved one at the time, e.g. the template Book above could be called "Template:Translation of "book"" or "Template:Translations of "book"". Similarly [[Template:Name of talk namespace]] could also be called Template:Names of talk namespaces.

Since editing a template in general can be considered a little more advanced than just using it by putting a template tag in a page, it can be argued that the naming can best be done from the point of view of people doing the latter, i.e. singular, just like in the case of a template for each array element: <nowiki>{{Translation of "book"|de}} just like the alternative {{Translation of "book" - de}}</nowiki>.

==In-page array content==
Instead of having a separate template to define the content of an array, the content of one or more arrays can be put in a template (or, if the array elements are selected based on a variable, it may also be a regular page) between other text.

In this case we have
*<nowiki>{{</nowiki>p''index'' |''value-1-of-index'' =''value-of-array-element-1'' |''value-2-of-index'' =''value-of-array-element-2'' |..}}
or if index values 1,2,3,.. are used, simply
*<nowiki>{{</nowiki>p''index'' |''value-of-array-element-1'' |''value-of-array-element-2'' |..}}

where ''index'' is an expression in terms of one or more parameters or variables.

Several arrays may use the same index value, to have corresponding selections of array elements, or different ones, e.g. to allow all combinations. An example of the former follows.

[[Template:Creature demo]] contains:
:<code>{{msgnw:creature demo}}</code>


'''''Choosing parameters contextually -''''' <code><nowiki>{{t pnd|parameter name}}</nowiki></code>
<blockquote>
* [[Template:t p]] contains <code><nowiki>{{{capital}}} is the capital of {{{country}}}</nowiki></code>, with two parameters - "capital" and "country".
* {{timc|t pnd}} can be used to select ''which'' parameter is used in a particular case.
Thus:
Thus:
*<nowiki>{{creature demo|1}}</nowiki> gives: {{creature demo|1}}
*<nowiki>{{creature demo|2}}</nowiki> gives: {{creature demo|2}}
*<nowiki>{{creature demo|3}}</nowiki> gives: {{creature demo|3}}


{| class="wikitable"
===Optional text===
|-
Due to the blank [[Template:P0]], in each selection an additional option is using index "0", giving no text. This allows putting a text which is optional, 1=on, 0=off.
!This...
!Produces this
|-
|{{tlx|t pnd|capital}}
|{{t pnd|capital}}
|-
|{{tlx|t pnd|country}}
|{{t pnd|country}}
|-
|{{tlx|t pnd|something else}}
|{{t pnd|something else}}
|}


This applies to integer parameters as well, since integer parameters can be specified using the "#=" notation. Passing the integer value N to {{tl|t pnd}} as its parameter will make it look for the Nth unnamed parameter.
(Note that a blank page cannot be created directly; first create a non-blank page, e.g. with just one character, then edit the page to blank it. )
</blockquote>
This is e.g. applied in [[w:Template:Reg polyhedra db]], which contains a 2D array in the form '''{{'''{{{1}}}'''|'''{{{2}}}'''|'''1-1=a11'''|'''..'''|'''m-n=amn'''}}'''. The first parameter is the name of a template that provides a particular selection and presentation of a selected row of the array, e.g. [[w:Template:Reg polyhedron stat table]], the second parameter (which is the first parameter of the latter template) specifies the row. The latter templates references element j of the row concerned by a tag of the form {{{{{{1}}}-j}}}


Whilst the same output could also be produced using {#switch:}, this method is less intensive on the server and may help to stay under page limits; see [[Help:Array]].
====Example====
;''Parameter name from another parameter in the same template'' - <code><nowiki>{{ppp|p=foo|foo=bar}}</nowiki></code>:
A parameter name is a wikitext that is expanded before being used as name.
For instance, using [[Template:ppp]], which contains <code><nowiki>{{{{{{p}}}}}}</nowiki></code> (six braces, the parameter name is itself a parameter), the code <code><nowiki>{{ppp|p=foo|foo=bar}}</nowiki></code> :
* Sets the parameter named {{{foo}}} to the value "bar", and then set the parameter named {{{p}}} to the value of foo. The order in which the parameters appear in the code does not matter.
* Then the content of [[:template:ppp]] is used, the parser analyzing it as <code><nowiki>{{{...}}}</nowiki></code> = a variable name.
** It then isolates the wikitext that takes place in this variable names, which is <code><nowiki>{{{p}}}</nowiki></code>.
** It then expands that wikitext, finding it to be a valid variable name.
** It replaces the variable name ''p'' by its wikitext value, yielding "foo".
* After inner expansion, the variable is therefore <code><nowiki>{{{foo}}}</nowiki></code>
* It replaces the variable name ''foo'' by its value, yielding "bar".
The result of the template call is therefore {{ppp|p=foo|foo=bar}}.


The name expansion is recursive, so the technique can be applied multiple times&mdash;e.g., using [[Template:tvvv]], which contains <code><nowiki>{{{{{{{{{p}}}}}}}}}</nowiki></code>, <code><nowiki>{{tvvv|p=foo|foo=bar|bar=biz}}</nowiki></code> gives :
[[Template:Variable text demo 1]] contains
* Variable initialization : {{{p}}} = "foo" ; {{{foo}}} = bar ; {{{bar}}} = "biz".
* Template expansion is {{{ ... }}} with parameter name = {{{{{{p}}}}}}.
** Parameter name expansion is {{{...}}} with parameter name = {{{p}}}.
*** Parameter name expansion is {{{...}}} with parameter name = "p".
*** Parameter {{{p}}} has been initiated to "foo" : expansion wikitext is "foo".
** Parameter {{{foo}}} has been initiated to "bar" : expansion wikitext is "bar".
* Parameter {{{bar}}} has been initiated to "biz" : expansion wikitext is "biz".
Result is {{tvvv|p=foo|foo=bar|bar=biz}}.


And so on, using [[Template:tvvvv]], which contains <code><nowiki>{{{{{{{{{{{{p}}}}}}}}}}}}</nowiki></code> (forth level indirection, twelve braces), <code><nowiki>{{tvvvv|p=alpha|alpha=beta|beta=gamma|gamma=delta}}</nowiki></code> gives {{tvvvv|p=alpha|alpha=beta|beta=gamma|gamma=delta}} (whatever use that may have).
*{{msg:Variable text demo 1}}


==Branching techniques without ParserFunctions==
<nowiki>{{Variable text demo 1|0}}</nowiki> gives
The parameter default feature was introduced before [[mw:Help:Extension:ParserFunctions|Extension:ParserFunctions]]. This led to the development of branching methods through the parameter default mechanism.
*{{Variable text demo 1|0}}


<nowiki>{{Variable text demo 1|1}}</nowiki> gives
;''If-defined branches'' - <code><nowiki>{{{test{{{test|}}}|{{{then}}}}}}</nowiki></code>:
* If no value is passed for the parameter test, then <nowiki>{{{test{{{test|}}}|{{{then}}}}}}</nowiki> resolves to <nowiki>{{{test|{{{then}}}}}}</nowiki> and returns the value of the parameter "then" (since no value was passed for test).
*{{Variable text demo 1|1}}
* If the parameter "test" is assigned the value "boo", however, <nowiki>{{{test{{{test|}}}|{{{then}}}}}}</nowiki> resolves to <nowiki>{{{testboo|{{{then}}}}}}</nowiki>, and so long as no parameter "testboo" exists, then this will return the value of the parameter "then".
* If the parameter "test" is defined but its value is empty, <nowiki>{{{test|}}}</nowiki> is defined and its value is empty, therefore <nowiki>{{{test|{{{then}}}}}}</nowiki> is defined and its value is empty.


See [[:Template:Ifwpc]] or [[Template:if]] for comparisons.
====Example with multiple similar lines====


There was also an [[Help:Array#Array technique using parameter defaults|array technique using parameter defaults]], with the disadvantage that a template using this technique had to be called with, in addition to the normal parameters, a standard parameter definition not reflecting a choice, but necessary to make the template work.
<nowiki>{{variable text demo|1}}</nowiki> gives the long version of a text:
{{variable text demo|1}}


An even older branching technique dates from before the introduction of the parameter default mechanism. It is based on the fact that if in a template call a parameter is assigned a value more than once, the last one counts. This is used in combination with specifying the value of a parameter in a template call, where the name of that parameter depends on a parameter of an outer template. In a call <code><nowiki>{{a|b=c|{{{d}}}=e}}</nowiki></code>, template:a uses b=c if b≠{{{d}}} and b=e if b={{{d}}}.
while <nowiki>{{variable text demo|0}}</nowiki> gives the short version:
{{variable text demo|0}}


Another old "branching technique" is using a template name depending on the value of a parameter (see above).
This construction uses the following templates:
*[[Template:Variable text demo]] (see [http://meta.wikimedia.org/w/index.php?title=Template:Variable_text_demo&action=edit wikitext]) - a template that produces a list, with, depending on a parameter ("comprehensiveness toggle"), either long versions of all items, or short versions; it contains all data that is not common to all lines
*[[Template:Variable line demo]] - defines the pattern of a list item, including which parts are only in the full version and which also in the short version; it contains the text that is common to all lines


==A variable name depending on a parameter==
== Variable variable names ==


;''Magic word depending on a template'' - <code><nowiki>{{t curr}}</nowiki></code>: {{timc|t curr}} gives the text ''{{CURRENT{{t day}}}}'' without parameters, since it defaults to <nowiki>{{CURRENTDAY}}</nowiki>, but {{tlx|t curr|DAYNAME}} gives ''{{t curr|DAYNAME}}'' while {{tlx|t curr|MONTHNAME}} gives ''{{t curr|MONTHNAME}}''. Any magic word that begins with "CURRENT" can be accessed this way.
Example:
;''Parser function parameter depending on a template parameter'' - <code><nowiki>{{ns:{{{1}}}}}</nowiki></code>: In [[Template:Namespace]], which contains "<code>{{msgnw:namespace}}</code>", <code><nowiki>{{namespace|4}}</nowiki></code> gives "{{namespace|4}}", because ''Meta'' is the name of namespace 4.


== External examples ==
<nowiki>{{namespace|4}}</nowiki>, using [[Template:Namespace]], containing
*VARIABLE MAGIC WORDS

**[[Template:H:h]] and [[Template:H:f]] (see edit pages, [[Help:MediaWiki_help_policy#Keeping_project-specific_material_separate|MediaWiki help policy]], and [http://meta.wikimedia.org/w/index.php?title=Special:Allpages/h&namespace=10 list])
:{{msgnw:namespace}}
**[[Template:Nsn]] - namespace number (see also below)

**[[Template:Gns]] - generic namespace name, useful for linking to the corresponding page on another project
gives:
**[[:de:MediaWiki:Newarticletext]] and [[:de:MediaWiki:Noarticletext]] (see edit pages and [http://de.wikipedia.org/w/index.php?title=Spezial:Allpages/MediaWiki&namespace=10 list])

**[[w:en:Template:H:f]] - for project-specific content on all help pages of the English Wikipedia (requires a blank template on all pages that do not have this content)
:{{namespace|4}}

==A parameter name depending on a parameter==
A parameter name in a template call (before "=") can depend on a parameter.

For example, using {{tcw|t pnd}} with {{tcw|t p}}:

<pre>
*{{t pnd|capital}}
*{{t pnd|country}}
*{{t pnd|something else}}
</pre>

gives

*{{t pnd|capital}}
*{{t pnd|country}}
*{{t pnd|something else}}

This applies also for integer parameter names which normally do not require "=", but are now referred to by an expression on the left of "=".


<!-- obsolete items hidden for the time being - need to review
Furthermore, multiple assignments of values to the same parameter in the same template call is allowed and result in the last value being used.


:'''''The following is somewhat obsolete on wikis with the [[ParserFunctions]] extension, which allows easier branching.'''''
For example, <nowiki>{{t p|country=Belgium|capital=Paris|country=France}}</nowiki> gives "{{t p|country=Belgium|capital=Paris|country=France}}".


This can be combined into the following branching technique:
This can be combined into the following branching technique:


<nowiki>{{</nowiki>tts|''first parameter, with fixed name''=do if parameter names are not equal|second parameter, with the name depending on parameters and/or variables=do if parameter names are equal}} with [[Template:Tts]] containing <nowiki>{{{{{</nowiki>''name of first parameter'' }}}}} (in this case that name is the empty string). The two parameter values, here called "do if parameter names are not equal" and "do if parameter names are equal" are the names of templates for the two alternative actions.
<nowiki>{{</nowiki>tts|''first parameter, with fixed name'' = ''name of template to be called if the parameter names are not equal'' | ''second parameter, with the name depending on parameters and/or variables'' = ''name of the template to be called if the parameter names are equal'' }} with [[Template:Tts]] containing <nowiki>{{{{{</nowiki>''name of first parameter'' }}}}} (in this case that name is the empty string).


Thus, while carrying out an action in the case of equality can also be done simply by using a template name equal to the constant (the fixed name above), this technique also allows an action in the case of ''in''equality, without having to cover all alternative values (different from the constant) separately.
Thus, while carrying out an action in the case of equality can also be done simply by using a template name equal to the constant (the fixed name above), this technique also allows an action in the case of ''in''equality, without having to cover all alternative values (different from the constant) separately.
Line 245: Line 178:
Example:
Example:


Branching depending on whether a parameter is empty is illustrated with {{ut|T pdc}}. Due to
Branching depending on whether a parameter is empty is illustrated with {{Tcw|T pdc}}.


*<nowiki>{{t pdc|abc}}</nowiki> gives {{t pdc|abc}}
*<nowiki>{{t pdc|abc}}</nowiki> gives {{t pdc|abc}}
*<nowiki>{{t pdc|}}</nowiki> gives {{t pdc|}}
*<nowiki>{{t pdc|}}</nowiki> gives {{t pdc|}}

Unfortunately there is no control over the result when the parameter is undefined (as opposed to empty):

*<nowiki>{{t pdc}}</nowiki> gives {{t pdc}}
*<nowiki>{{t pdc}}</nowiki> gives {{t pdc}}


Example with an extra parameter:
Example with an extra parameter:


Consider {{ut|ine}}: '''I'''f the first parameter is '''N'''ot '''E'''mpty then do the task given by the second parameter with the first parameter as its parameter, else do nothing.
Consider {{timc|ine}}, which calls {{timc|call}}: '''I'''f the first parameter is '''N'''ot '''E'''mpty then do the task given by the first parameter with the second, third and fourth parameter as its parameters, else do nothing; if the number of parameters of the task is 0, 1, or 2, ignore the superfluous values.


Using {{ut|Death}}:
Using {{timc|Death}}:


*<nowiki>{{ine|[[November 2]], [[2004]]|death}}</nowiki> gives "{{ine|[[November 2]], [[2004]]|death}}".
*<nowiki>{{ine|death|[[November 2]], [[2004]]|[[Amsterdam]]|}}</nowiki> gives:
*<nowiki>{{ine||death}}</nowiki> gives "{{ine||death}}".


"{{ine|death|[[November 2]], [[2004]]|[[Amsterdam]]|}}".
This can be useful inside another template, with a tag like <nowiki>{{ine|{{{date of death}}}|death}}</nowiki>, to avoid showing the text "Date of death:" for a living person, and also avoid having to put this text in the parameter for all dead people.
*<nowiki>{{ine|death||comment|}}</nowiki> gives "{{ine|death||comment|}}".


This can be useful inside another template, to avoid the texts "Date of death:" and "place of death:" for a living person.
Similarly, where a table row dealing with a parameter is removed if the parameter is empty:


Also, without a separate template Death, with just the more general {{timc|p2p1p3}}:
[[w:en:Template:If defined call1]] calls [[w:en:Template call1]] with 1={{{2}}} followed by 1{{{1}}}=void; if {{{1}}} is empty then this overwrites the value of 1, so 1=void, otherwise 1={{{2}}}, giving an empty result or {{{{{2}}}|{{{3}}}}}. {{{3}}} is typically the same as {{{1}}} (at least that is the case in all five cases in [[w:en:Template:Infobox CVG]]). It avoids e.g. the text "Designer:" if the parameter {{{designer}}} is empty.


*<nowiki>{{ine|p2p1p3|[[November 2]], [[2004]]|Date of death:&nbsp; |, place of death: [[Amsterdam]]}}</nowiki> gives:
More generally, using {{ut|T pdcg}} with {{ut|tts5}}:


"{{ine|p2p1p3|[[November 2]], [[2004]]|Date of death:&nbsp; |, place of death: [[Amsterdam]]}}".
*<nowiki>{{T pdcg|3}}</nowiki> gives {{T pdcg|3}}
*<nowiki>{{T pdcg|4}}</nowiki> gives {{T pdcg|4}}
*<nowiki>{{T pdcg|5}}</nowiki> gives {{T pdcg|5}}
*<nowiki>{{T pdcg|6}}</nowiki> gives {{T pdcg|6}}
*<nowiki>{{T pdcg|}}</nowiki> gives {{T pdcg|}}


This would not be convenient to use in many template tags, but could be used in an infobox in the form
However:


*<nowiki>{{T pdcg}}</nowiki> gives {{T pdcg}}
*<nowiki>{{</nowiki>ine|p2p1p3|{{{1}}}|Date of death:&nbsp; |, place of death: {{{2}}}}}


(Alternatively a separate parameter "dead" with one of the values "dead" and "alive" is used, see, e.g., [[w:en:Template:Infobox President]] with the auxiliary templates [[w:en:Template:Infobox President/dead]] and the empty [[w:en:Template:Infobox President/alive]]. A disadvantage is the extra parameter: it has to be specified that a president is alive, it is not sufficient to leave the date of death empty, or that a president is dead, even if a date of death has been specified. An advantage is that backlinks are available, providing not only a list of dead, but also a list of alive presidents for which the infobox is used.)


Similarly, where a table row dealing with a parameter is removed if the parameter is empty:
A parameter name in a parameter tag can ''not'' depend on a parameter, see [[Template:T pnd1]] and its talk page.


[[w:en:Template:If defined call1]] calls [[w:en:Template:Template_call1]] with 1={{{2}}} followed by 1{{{1}}}=void; if {{{1}}} is empty then this overwrites the value of 1, so 1=void, otherwise 1={{{2}}}, giving an empty result or {{{{{2}}}|{{{3}}}}}. {{{3}}} is typically the same as {{{1}}} (at least that is the case in all five cases in [[w:en:Template:Infobox CVG]]). It avoids e.g. the text "Designer:" if the parameter {{{designer}}} is empty.
Also a parameter name in a template call can ''not'' depend on a variable:
while <nowiki>{{ns:2}}</nowiki> gives {{ns:2}}
and <nowiki>{{PUser|User=abc}}</nowiki> gives {{PUser|User=abc}},
<nowiki>{{PUser|{{ns:2}}=abc}}</nowiki> gives {{PUser|{{ns:2}}=abc}}


More generally, using {{timc|If equal g}}:
==Impossibility to include the content of a template in a template name, variable name, or parameter value==


*<nowiki>{{if equal g|2x|3x|{{NAMESPACE}}|Help|a||}}</nowiki> gives {{if equal g|2x|3x|{{NAMESPACE}}|Help|a||}}
It is not possible to use a template with a name dependent on the content of another template.
*<nowiki>{{if equal g|2x|3x|Help|{{NAMESPACE}}|a||}}</nowiki> gives {{if equal g|2x|3x|Help|{{NAMESPACE}}|a||}}
*<nowiki>{{if equal g|2x|3x|{{NAMESPACE}}|Template_talk|a||}}</nowiki> gives {{if equal g|2x|3x|{{NAMESPACE}}|Template_talk|a||}}
*<nowiki>{{if equal g|2x|3x|Template_talk|{{NAMESPACE}}|a||}}</nowiki> gives {{if equal g|2x|3x|Template_talk|{{NAMESPACE}}|a||}}


Note that <nowiki>{{</nowiki>NAMESPACE}} produces underscores for spaces, which are not considered equal by the template:
:For example: <nowiki>{{{{tctc}}}}</nowiki> is trying to include a template on a page, using the text in [[Template:Tctc]] to get the name of the template. However, <nowiki>{{{{tctc}}}}</nowiki> simply gives the text {{{{tctc}}}}, not the content of the template named in Tctc.


*<nowiki>{{if equal g|2x|3x|Template_talk|Template talk|a||}}</nowiki> gives {{if equal g|2x|3x|Template_talk|Template talk|a||}}
It is not possible to use a variable with a name dependent on the content of a template.
*<nowiki>{{if equal g|2x|3x|Template_talk|Template_talk|a||}}</nowiki> gives {{if equal g|2x|3x|Template_talk|Template_talk|a||}}


==Producing the value of a parameter whose name depends on the value of another parameter==
:For example: <nowiki>{{CURRENT{{t day}}}}</nowiki> using [[Template:T day]] gives the text {{CURRENT{{t day}}}}, not its value.


The technique can also be used to create control flow structures. An ''ifdef''-function as in {{tim|ifdef}} could look like:
It is not possible to include the content of another template in a parameter value
<nowiki>{{{test{{{test|}}}|{{{then}}}}}}</nowiki>
If '''test''' is empty, we expand the empty '''test''' parameter, but if it contains data, then after trying to expand a non-existing
'''test''data'''''-parameter, we get the '''then'''-parameter value instead. Or a literal {&#123;{then}&#125;}, if there's intentionaly
no default value for '''then''', and '''then''' is undefined - a crude mechanism to catch errors.


Of course, this fails for a, say, '''test''' value ''it'' if '''testit''' is defined. An example with numerical parameters:
:For example: <nowiki>{{x3|{{tc}}}}</nowiki>, using [[Template:x3]], gives {{x3|{{tc}}}}. The first pair of end braces is matched to the first pair of start braces (not to the "inner pair" of start braces, as you might expect). Thus, "{{tc" is interpreted as the parameter value.
<nowiki>{{{1{{{1|}}}|okay}}}</nowiki>
For a defined first parameter, we expect to get the text ''okay''. But if the value of the first parameter is, say, 0, and a tenth parameter
exists, we get its value {&#123;{10}&#125;} instead of ''okay''.


It's slightly different for an ''ifndef''-function as in {{tim|ifndef}}:
In particular, a template name, variable name, and parameter value cannot depend on an "array value" as explained above. To allow branching based on an array element, the method of having a template for each array element can be used, provided that plain text like "Allemand" is replaced by a template call such as <nowiki>{{</nowiki>lang name|Allemand|''parameter'' }}, where the parameter can be used to choose between e.g. just displaying the text or using it in another template name or parameter.
<nowiki>{{{then{{{test|}}}|}}}</nowiki>
If '''test''' is empty, then we expand the '''then''' parameter. But if '''test''' contains data, then we try to expand a nonexisting '''then''data'''''-parameter,
finally arriving at its empty default value (= after the second "|" pipe symbol).


Again this fails if the non-existing parameter in fact does exist, e.g., for
For example, a template like [[Template:Hist5]] for displaying a histogram can not be applied to an array in the sense explained above, but if an array element is 38, and this value is not put in a template in plain text but in the form <nowiki>{{a|38|{{{code}}}}}</nowiki>, then depending on the value of ''code'' the number can just be displayed, or displayed as a histogram bar, etc. These actions can be defined in Template:A which calls Template:A''code''.
<nowiki>{{{x{{{1|}}}|}}}</nowiki>
with a defined value ''y'' for '''x''' we expect to get the empty default for a non-existing '''xy'''. This fails if {&#123;{xy}&#125;} is defined and non-empty.


An if-then-else could be a combination of those two, as in {{timc|ifold}}.
==Template producing the name of the talk namespace of the calling page==
In English language projects the name of a talk namespace is usually simply "<nowiki>{{NAMESPACE}}</nowiki> talk", here giving {{NAMESPACE}} talk. With this a link can be produced:
<nowiki>[[{{NAMESPACE}} talk:{{PAGENAME}}]]</nowiki> giving [[{{NAMESPACE}} talk:{{PAGENAME}}]]


For simple ''ifdef''-cases the best solution is arguably to use it without additional template, e.g. for text relevant only if the third positional parameter is defined use:
Also one could include a todo page in the corresponding talk namespace associated with each no-talk page; from the no-talk namespace it can be done with <nowiki>{{{{NAMESPACE}} talk:{{PAGENAME}}/todo}}</nowiki> wich gives {{{{NAMESPACE}} talk:{{PAGENAME}}/todo}} (a link to a non-existing template page or an inclusion of the content). From the no-talk namespace it can be done with <nowiki>{{{{NAMESPACE}}:{{PAGENAME}}/todo}}</nowiki>.
<nowiki>{{{3{{{3|}}}|found third parameter}}}</nowiki>
For the opposite ''ifndef''-case there's unfortunately no similar direct approach.
Substitution works for [[Template:ifdef|ifdef]], but not [[Template:ifndef|ifndef]] or [[Template:ifold|ifold]].


A parameter value can also be used as ''part'' of the name of another parameter:
Using [[Template:Name of talk namespace]] (after completing the list of namespaces) with the corresponding auxiliary templates like [[Template:PUser]] (for general use of arrays with the namespace as index), the linking can be done in all languages:
<pre>

{{switch
<nowiki>[[{{Name of talk namespace}}:{{PAGENAME}}/todo]]</nowiki> gives [[{{Name of talk namespace}}:{{PAGENAME}}/todo]].
|{{CURRENTDOW}}

|case: 1=Mon
Alternatively, a separate template is created for each namespace just for this purpose, see [http://en.wikipedia.org/w/index.php?title=Special%3AAllpages&from=ARTICLESPACE&namespace=10].
|case: 2=Tue

|case: 3=Wed
However, these methods work for linking but not for including. One can use <nowiki>{{{{NAMESPACE}}:{{PAGENAME}}/todo}}</nowiki> but if applied in the no-talk and the talk namespace, this gives two todo pages unless a redirect is created.
|case: 4=Thu

|case: 5=Fri
Therefore, in addition two new variables are being prepared for a new version of the software. When that works one can use, both from the non-talk page and the talk page:
|case: 6=Sat
*<nowiki>{{{{NAMESPACE_TALK}}:{{PAGENAME}}/to_do}}</nowiki>
|case: 0=Sun

|default=No date
Test whether they work already:
}}
* <nowiki>{{NAMESPACE_TALK}}</nowiki> gives {{NAMESPACE_TALK}}
</pre>
* <nowiki>{{NAMESPACE_NO_TALK}}</nowiki> gives {{NAMESPACE_NO_TALK}}

See also [http://bugzilla.wikimedia.org/show_bug.cgi?id=531 Bug 531].


using {{timc|switch}} gives {{switch
==Illustration of the possibilities of template calls and links==
|{{CURRENTDOW}}
[[Template:T complex]] contains:
|case: 1=Mon
|case: 2=Tue
|case: 3=Wed
|case: 4=Thu
|case: 5=Fri
|case: 6=Sat
|case: 0=Sun
|default=No date
}}


Using this technique and an auxiliary template, we can produce a function that checks if two parameter values are the same:
{{msgnw:T complex}}


{{timc|equal}}, with {{timc|vv2}}.
Using <nowiki>{{tcw|t complex}}</nowiki> gives:


It will return 1 if equal, or null (the empty string) if not.
{{t complex|c=d|g=h|k=m|q=r|u=v|y=z|eMetafhh=abc}}


-->
==See also==
== See also ==
*[[Meta_talk:Templates_for_translating_language_names]]
* [[mw:Help:Extension:ParserFunctions|ParserFunctions]] (syntax for <code><nowiki>#if:, #expr:</nowiki></code>, etc.)
* [[Meta talk:Templates for translating language names]]
* [[Help:Array]]


{{h:f|enname=Advanced templates}}
{{h:f|enname=Template names, variable names and parameters depending on a variable or parameter }}

Latest revision as of 21:32, 13 December 2023


This page covers advanced template techniques, particularly, the use of variable template names, and parameter names in templates. Readers, should first be thoroughly familiar with the standard template techniques, found in Help:Template. Some of the techniques described below, may be outdated or of limited use; for example, ParserFunctions and Lua, may be more convenient alternatives to using some of the branching techniques discussed.

In general, these techniques rely on the recursive (inside-out) processing of templates. When a template is expanded (processed), it translates the given template code into string values. These are often sent directly to the web browser for display, however, they can be treated as code themselves. For instance, by enclosing the text strings in double-curly-brackets ( {{}} ), they can be reprocessed as template names or variable names; thus, producing different results as the string values are changed.

Notes:

  • This document refers to features that are currently, only available in the mw:Mediawiki software, starting with version 1.6 and later.
  • The term "variable" has two uses in this document:
Variable (n.)
refers to a type of magic word——a system-based variable that can be accessed in the same manner as templates——thus, {{NAMESPACE}} will return the name of the current namespace, depending on the page.
Variable (adj. or adv.)
used in a general sense to indicate that parts within the context may vary; hence, a variable template name, states that the name of the template being called, can be changed, according to the parameters or variables.
  • Using "subst:" with manual recursion, gives a step–wise replacement, useful for analyzing and explaining the working of templates calling other templates. For instance, compare {{{{tctc}} }} (discussed below) with {{{{subst:tctc}} }}, on a sandbox page. Although both produce the same visible result, the first will remain as the full code {{{{tctc}} }}, while the second will replace the inner template {{tctc}} with its value, leaving the code {{tc }}.


Variable templates

In some cases, it may be useful for a template to call different templates depending on a variable or a passed parameter. This allows a type of branching that can be simpler than with ParserFunctions, though they are generally less versatile.

Examples:

Using a variable to choose a template - {{ {{NAMESPACE}}}}
The magic word {{NAMESPACE}} returns the current namespace, like so: {{NAMESPACE}} = Help. The outer brackets then process this result as a template in its own right - in this case Template:Help - which produces This phrase is the contents of Template:Help.
Using a template to choose a template - {{ {{tctc}}}}
the template {{Tctc}} contains the text "tc". This text is processed by the outer brackets as Template:tc which contains the word "in".

The extra spaces in the above examples are needed: without them, the pair of inner three braces is taken as those for a parameter. On the page itself it just shows as plain text: {{{{Help}}}}.

Using a parameter to choose a template - {{{{{2}}}x|{{{1}}}}}
The second parameter passed becomes part of the template name to which the first parameter is passed. In this case {{2x|{{{1}}}}} would produce {{{1}}}{{{1}}}, {{3x|{{{1}}}}} would produce {{{1}}}{{{1}}}{{{1}}}, and etc. Template:Hist5 uses this technique repeatedly in {{hist5|X|4|7|3|2|9}} to produce the following 5 line histogram:

XXXX

XXXXXXX
XXX
XX

XXXXXXXXX

Using parser functions and templates, including those which process strings (see Help:String functions and Category:String manipulation templates), a template name can also depend in a more complicated way on parameters and/or variables.

Templates passed as parameters

Templates can be passed as parameters to other templates. This can mean either that the template is evaluated and the result is passed as a parameter or that the template name is passed and evaluated as part of the other template.

Passing a template result - {{3x|{{tc}}}}
Template:3x contains {{{1}}}{{{1}}}{{{1}}}. {{3x|{{tc}}}} first evaluates {{tc}} (which yields in), and passes that to template {{3x}}, to give ininin.
Passing a template result recursively - {{3x|{{5x|{{tc}}}}}}
Just as above except {{tc}} (in) is first passed to {{5x}} and the result of that is passed to {{3x}}, to give ininininininininininininininin.
Passing a template name - {{tto|t|V}}
Template:tto - {{{{{1}}}|a{{{2}}}b{{{2}}}c{{{2}}}d}} - takes the value V (passed as the second parameter) and produces aVbVcVd. This value is then passed to template:t (which was passed by name as the first parameter), producing "start-aVbVcVd-end".

In interpreting this sequence {{tto|t|V}}, the parser :

  1. sees that {{tto|t|V}} is formally a valid template call, with :
    • template name = "tto"
    • parameter 1 = "t"
    • parameter 2 = "V"
  2. evaluates the current values both of the template name and of its parameter,
  3. gets the current value of the template content {{{{{1}}}|a{{{2}}}b{{{2}}}c{{{2}}}d}}
    1. (recursively) sees that {{{{{1}}}|a{{{2}}}b{{{2}}}c{{{2}}}d}} formally contains a valid template call, with :
      • template name = {{{1}}}
      • parameter 1 = a{{{2}}}b{{{2}}}c{{{2}}}d
    2. evaluates the current values both of the template name and of its parameter, in the context where {{{1}}} = b and {{{2}}} = V, giving :
      • template name = b
      • parameter 1 = aVbVcVd
    3. gets the current value of the template content start-{{{1}}}-end
    4. applies the template to its parameters, producing "start-aVbVcVd-end".
  4. (recursively) returns the value.

Variable parameter name

A parameter name in a template can be the value of another parameter. This is useful if you want the behavior of a template to change based on the information that is provided to it.

Choosing parameters contextually - {{t pnd|parameter name}}

  • Template:t p contains {{{capital}}} is the capital of {{{country}}}, with two parameters - "capital" and "country".
  • Template:t pnd containing "{{t p|{{{1}}}=abc}}" can be used to select which parameter is used in a particular case.

Thus:

This... Produces this
{{t pnd|capital}} abc is the capital of {{{country}}}.
{{t pnd|country}} {{{capital}}} is the capital of abc.
{{t pnd|something else}} {{{capital}}} is the capital of {{{country}}}.

This applies to integer parameters as well, since integer parameters can be specified using the "#=" notation. Passing the integer value N to {{t pnd}} as its parameter will make it look for the Nth unnamed parameter.

This is e.g. applied in w:Template:Reg polyhedra db, which contains a 2D array in the form {{{{{1}}}|{{{2}}}|1-1=a11|..|m-n=amn}}. The first parameter is the name of a template that provides a particular selection and presentation of a selected row of the array, e.g. w:Template:Reg polyhedron stat table, the second parameter (which is the first parameter of the latter template) specifies the row. The latter templates references element j of the row concerned by a tag of the form {{{{{{1}}}-j}}}

Whilst the same output could also be produced using {#switch:}, this method is less intensive on the server and may help to stay under page limits; see Help:Array.

Parameter name from another parameter in the same template - {{ppp|p=foo|foo=bar}}

A parameter name is a wikitext that is expanded before being used as name. For instance, using Template:ppp, which contains {{{{{{p}}}}}} (six braces, the parameter name is itself a parameter), the code {{ppp|p=foo|foo=bar}} :

  • Sets the parameter named {{{foo}}} to the value "bar", and then set the parameter named {{{p}}} to the value of foo. The order in which the parameters appear in the code does not matter.
  • Then the content of template:ppp is used, the parser analyzing it as {{{...}}} = a variable name.
    • It then isolates the wikitext that takes place in this variable names, which is {{{p}}}.
    • It then expands that wikitext, finding it to be a valid variable name.
    • It replaces the variable name p by its wikitext value, yielding "foo".
  • After inner expansion, the variable is therefore {{{foo}}}
  • It replaces the variable name foo by its value, yielding "bar".

The result of the template call is therefore bar.

The name expansion is recursive, so the technique can be applied multiple times—e.g., using Template:tvvv, which contains {{{{{{{{{p}}}}}}}}}, {{tvvv|p=foo|foo=bar|bar=biz}} gives :

  • Variable initialization : {{{p}}} = "foo" ; {{{foo}}} = bar ; {{{bar}}} = "biz".
  • Template expansion is {{{ ... }}} with parameter name = {{{{{{p}}}}}}.
    • Parameter name expansion is {{{...}}} with parameter name = {{{p}}}.
      • Parameter name expansion is {{{...}}} with parameter name = "p".
      • Parameter {{{p}}} has been initiated to "foo" : expansion wikitext is "foo".
    • Parameter {{{foo}}} has been initiated to "bar" : expansion wikitext is "bar".
  • Parameter {{{bar}}} has been initiated to "biz" : expansion wikitext is "biz".

Result is biz.

And so on, using Template:tvvvv, which contains {{{{{{{{{{{{p}}}}}}}}}}}} (forth level indirection, twelve braces), {{tvvvv|p=alpha|alpha=beta|beta=gamma|gamma=delta}} gives delta (whatever use that may have).

Branching techniques without ParserFunctions

The parameter default feature was introduced before Extension:ParserFunctions. This led to the development of branching methods through the parameter default mechanism.

If-defined branches - {{{test{{{test|}}}|{{{then}}}}}}
  • If no value is passed for the parameter test, then {{{test{{{test|}}}|{{{then}}}}}} resolves to {{{test|{{{then}}}}}} and returns the value of the parameter "then" (since no value was passed for test).
  • If the parameter "test" is assigned the value "boo", however, {{{test{{{test|}}}|{{{then}}}}}} resolves to {{{testboo|{{{then}}}}}}, and so long as no parameter "testboo" exists, then this will return the value of the parameter "then".
  • If the parameter "test" is defined but its value is empty, {{{test|}}} is defined and its value is empty, therefore {{{test|{{{then}}}}}} is defined and its value is empty.

See Template:Ifwpc or Template:if for comparisons.

There was also an array technique using parameter defaults, with the disadvantage that a template using this technique had to be called with, in addition to the normal parameters, a standard parameter definition not reflecting a choice, but necessary to make the template work.

An even older branching technique dates from before the introduction of the parameter default mechanism. It is based on the fact that if in a template call a parameter is assigned a value more than once, the last one counts. This is used in combination with specifying the value of a parameter in a template call, where the name of that parameter depends on a parameter of an outer template. In a call {{a|b=c|{{{d}}}=e}}, template:a uses b=c if b≠{{{d}}} and b=e if b={{{d}}}.

Another old "branching technique" is using a template name depending on the value of a parameter (see above).

Variable variable names

Magic word depending on a template - {{t curr}}
Template:t curr containing "{{CURRENT{{{1|DAY}}} }}<noinclude>[[Category:Test pages]]</noinclude>" gives the text 5 without parameters, since it defaults to {{CURRENTDAY}}, but {{t curr|DAYNAME}} gives Sunday while {{t curr|MONTHNAME}} gives May. Any magic word that begins with "CURRENT" can be accessed this way.
Parser function parameter depending on a template parameter - {{ns:{{{1}}}}}
In Template:Namespace, which contains "namespace number:{{{1}}} - name: {{ns:{{{1}}}}}", {{namespace|4}} gives "namespace number:4 - name: Meta", because Meta is the name of namespace 4.

External examples

See also

Links to other help pages

Help contents
Meta · Wikinews · Wikipedia · Wikiquote · Wiktionary · Commons: · Wikidata · MediaWiki · Wikibooks · Wikisource · MediaWiki: Manual · Google
Versions of this help page (for other languages see further)
What links here on Meta or from Meta · Wikipedia · MediaWiki
Reading
Go · Search · Namespace · Page name · Section · Backlinks · Redirect · Category · Image page · Special pages · Printable version
Tracking changes
Recent changes (enhanced) | Related changes · Watching pages · Diff · Page history · Edit summary · User contributions · Minor edit · Patrolled edit
Logging in and preferences
Logging in · Preferences
Editing
Starting a new page · Advanced editing · Editing FAQ · Export · Import · Shortcuts · Edit conflict · Page size
Referencing
Links · URL · Interwiki linking · Footnotes
Style and formatting
Wikitext examples · CSS · Reference card · HTML in wikitext · Formula · Lists · Table · Sorting · Colors · Images and file uploads
Fixing mistakes
Show preview · Reverting edits
Advanced functioning
Expansion · Template · Advanced templates · Parser function · Parameter default · Magic words · System message · Substitution · Array · Calculation · Transclusion
Others
Special characters · Renaming (moving) a page · Preparing a page for translation · Talk page · Signatures · Sandbox · Legal issues for editors
Other languages: