Jump to content

Help:Advanced templates: Difference between revisions

From Meta, a Wikimedia project coordination wiki
Content deleted Content added
m clean up, replaced: Help:Template → mw:Help:Template (2)
Replaced content with "{{MovedToMediaWiki|Manual:Advanced templates}}"
Tag: Replaced
 
Line 1: Line 1:
{{MovedToMediaWiki|Manual:Advanced templates}}
{{H:h}}[[Category:Editor handbook]]


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 [[mw: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.

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.

'''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 [[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>.


== Variable templates ==

<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:'''
<!-- 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. -->

;''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:

<blockquote>{{hist5|X|4|7|3|2|9}}</blockquote>

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.

== 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'' - <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}}}}.
;''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
Thus, it is also possible to use a data array as a parameter of a template, e.g.,:

<nowiki>{{</nowiki>hist5a|x|t data}} using

{{timcnl|hist5a}} and

{{timc|t data}} gives:

{{hist5a|x|t data}}
-->
;''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 :
# 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 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 -''''' <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:

{| class="wikitable"
|-
!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.
</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]].
;''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 :
* 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).

==Branching techniques without ParserFunctions==
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.

;''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).
* 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.

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.

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}}}.

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'' - <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.
;''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 ==
*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])
**[[Template:Nsn]] - namespace number (see also below)
**[[Template:Gns]] - generic namespace name, useful for linking to the corresponding page on another project
**[[: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)

<!-- obsolete items hidden for the time being - need to review

:'''''The following is somewhat obsolete on wikis with the [[ParserFunctions]] extension, which allows easier branching.'''''

This can be combined into the following branching technique:

<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.

Example:

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|}}</nowiki> gives {{t pdc|}}
*<nowiki>{{t pdc}}</nowiki> gives {{t pdc}}

Example with an extra parameter:

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 {{timc|Death}}:

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

"{{ine|death|[[November 2]], [[2004]]|[[Amsterdam]]|}}".
*<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.

Also, without a separate template Death, with just the more general {{timc|p2p1p3}}:

*<nowiki>{{ine|p2p1p3|[[November 2]], [[2004]]|Date of death:&nbsp; |, place of death: [[Amsterdam]]}}</nowiki> gives:

"{{ine|p2p1p3|[[November 2]], [[2004]]|Date of death:&nbsp; |, place of death: [[Amsterdam]]}}".

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

*<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:

[[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.

More generally, using {{timc|If equal g}}:

*<nowiki>{{if equal g|2x|3x|{{NAMESPACE}}|Help|a||}}</nowiki> gives {{if equal g|2x|3x|{{NAMESPACE}}|Help|a||}}
*<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:

*<nowiki>{{if equal g|2x|3x|Template_talk|Template talk|a||}}</nowiki> gives {{if equal g|2x|3x|Template_talk|Template talk|a||}}
*<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==

The technique can also be used to create control flow structures. An ''ifdef''-function as in {{tim|ifdef}} could look like:
<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:
<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}}:
<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
<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}}.

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:
<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:
<pre>
{{switch
|{{CURRENTDOW}}
|case: 1=Mon
|case: 2=Tue
|case: 3=Wed
|case: 4=Thu
|case: 5=Fri
|case: 6=Sat
|case: 0=Sun
|default=No date
}}
</pre>

using {{timc|switch}} gives {{switch
|{{CURRENTDOW}}
|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:

{{timc|equal}}, with {{timc|vv2}}.

It will return 1 if equal, or null (the empty string) if not.

-->
== See also ==
* [[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}}

Latest revision as of 23:42, 28 June 2024