User:Happy-melon/Templates

From MediaWiki.org
Jump to: navigation, search
Merge-arrows.svg It has been suggested that this article or section be merged with Help:Template. (Discuss)

The MediaWiki software includes the capacity to include the contents of one page in the display of another page - this process is known as transclusion. Since one page can be transcluded on many other pages, the most common use of transclusion is to create boilerplate text, which can be displayed on many pages but updated easily from one location. For this reason, pages which are created primarily for the purpose of being transcluded on other pages are known as templates. Most wikis include a "Template:" help:namespace to house these templates.

This page and its extension Help:Advanced templates form a reference manual for how to use templates and the associated wikimarkup on MediaWiki. Templates can also make use of other features of the MediaWiki software, such as ParserFunctions.

Note: The master version of this page is held at m:Help:Template on Meta-Wiki. All links and template examples work correctly there, but may not if you are viewing a copy of this page on another project.

Introduction[edit | edit source]

Most MediaWiki sites include a Template namespace which holds pages designed specifically for transclusion on other pages. A page within the Template: namespace is known as a template, although it is no different to any other page: the same wikimarkup can be used on templates as on any other page. However, many Wikipedias and other MediaWiki sites have policies to restrict the type of content that can appear in the Template: namespace. A page in the template namespace can be linked to like any other page: Template:TEx1 is a link to an example template that will be used later.

If you type Where Template:TEx1 contains You get
[[Template:TEx1]] [[:Template:TEx1]] Template:TEx1

This example format will be used throughout this documentation page. If, instead of enclosing the link in square brackets [[...]], the link is enclosed in braces {{...}}, this is a signal to the MediaWiki parser to transclude the page at that point, rather than link to it. Note that when using braces {{...}}, the page to be transcluded defaults to the Template: namespace if no other namespace is specified. To transclude a page in another namespace, the full pagename must be specified. So to transclude this page's talk page (User talk:Happy-melon/Templates), type {{User talk:Happy-melon/Templates}}. To transclude a page from the main namespace, use an 'empty' namespace field; to transclude the Main Page, you would need to type {{:Main Page}}. Not all namespaces can necessarily be transcluded, for various reasons. Attempting to transclude a page from a namespace which cannot be transcluded simply produces a link to the target page: {{Image:Foo.jpg}}File:Foo.jpg. Trying to transclude a non-existent page produces a redlink: {{SomeNonExistentPage}}Template:SomeNonExistentPage. The process of transcluding a template in the manner shown above has several synonyms, including: inclusion and embedding; however inclusion is sometimes used to mean substitution, which is entirely different. The code within the curly braces is often known as a template call. So:

If you type Where Template:TEx1 contains You get
{{Template:TEx1}} [[:Template:TEx1]] Template:TEx1
{{TEx1}} Template:TEx1
abc{{TEx1}}def abcTemplate:TEx1def

It is not possible to transclude pages across projects: trying to transclude w:de:Vorlage:User en anywhere but the German wikipedia outputs: {{w:de:Vorlage:User en}}.


Whatlinkshere[edit | edit source]

The MediaWiki software maintains a record of all template transclusions on a particular wiki, and displays this information where it is useful. When viewing Special:WhatLinksHere/Foo for a page Foo, any other pages which transclude Foo are noted as "transclusion". When editing a page or section of a page which transcludes templates, a list of all such templates is given at the bottom of the edit screen. The list is compiled and updated after each edit to the page, and is not updated when the page is recached or purged. This has several caveats:

  • Editing an old version of the page will cause the current list of transcluded pages to be displayed, even if they are not transcluded in the old version
  • Editing a section of a page will display the full list, even if some of the pages are not transcluded in that section.
  • If templates are transcluded via conditional statements, only those templates which are transcluded on the current version of the page are included: if the code {{#if:1|{{TEx1<nowiki>}}|{{TEx2}} }} were included on a page, only Template:TEx1 will be marked as transcluded.

Pressing the "show preview" button generates a new temporary templatelinks table, resulting in a correct list of the templates used in the current version, section and display of the page being edited.

Passing parameters[edit | edit source]

While some templates simply include only text, most include customizable values called parameters. Parameters are inside triple braces: {{{name}}} in the wiki code. When the page is transcluded to a page, the contents of the parameter name will be included in the text on that page.

If you type Where Template:TEx2 contains You get
{{TEx2|1=Hello World!}} [[:Template:TEx2]] Template:TEx2
{{TEx2|Hello World!}} Template:TEx2
{{TEx2|2=Hello World!}} Template:TEx2
{{TEx2||Hello World!}} Template:TEx2

By default, the parameters are numbered in order, starting from 1; there is no practical limit to the number of parameters that can be defined (at least 65536). However, named parameters may be added at any point without interrupting the numbering:

If you type Where Template:TEx3 contains You get
{{TEx3|A|B|C}} [[:Template:TEx3]] Template:TEx3
{{TEx3|A| B |x=C}} Template:TEx3
{{TEx3|A|x= B | C }} Template:TEx3
{{TEx3|A|x=B|x=C}} Template:TEx3
{{TEx3|1=A|2=B|=C}} Template:TEx3

Some points to note from these examples:

  • If no parameter name is specified, the value is assigned to the first unused numbered parameter.
  • Parameters cannot be 'overloaded' - if a parameter is assigned a value more than once, only the last value is retained
  • Whitespace is stripped from before and after named parameters (it is not always stripped from unnamed parameters).
  • It is possible to assign values to the 'null' parameter by using |=value. These values will not normally be displayed (although the null parameter can be referenced using {{{}}}).

Based on these concepts, it is possible to develop some quite sophisticated template layouts. A good real example is w:en:Template:Chess position on the english wikipedia. This template takes 65 unnamed parameters, but to standardise the layout of the wikicode dummy parameters are used:

Typing Produces
{{chess position|=

 8 |rd|nd|bd|qd|kd|bd|nd|rd|=
 7 |  |pd|pd|pd|pd|pd|pd|pd|=
 6 |pd|  |  |  |  |  |  |  |=
 5 |  |  |  |  |  |  |  |  |=
 4 |  |pl|  |  |  |  |pl|  |=
 3 |  |  |  |  |  |  |  |bl|=
 2 |pl|  |pl|pl|pl|pl|  |pl|=
 1 |rl|nl|bl|ql|kl|  |nl|rl|=
    a  b  c  d  e  f  g  h
|20}}
Template:Chess position

In this template call, the row numbers and column numbers are repeatedly assigned to the null parameter using the code |=. The template call is syntactically equivalent to {{chess position|rd|nd|bd|qd|kd|bd|nd|rd||pd|pd|pd|pd|pd|pd|pd|pd|||||||||||||||||pl|||||pl|||||||||bl|pl||pl|pl|pl|pl||pl|rl|nl|bl|ql|kl||nl|rl|20}}, but is much easier to understand.

Restrictions on parameter values[edit | edit source]

Equals signs[edit | edit source]

Unnamed parameter values cannot contain equals signs. Named parameters can contain equals signs. This is most commonly seen with User signatures containing HTML code. Imagine a signature: <font color=red>[[User:Example|Example]]</font>, which would display as Example. If this code were passed to a template as an unnamed parameter (eg {{TEx2|<font color=red>[[User:Example|Example]]</font>}}, then when the template is parsed, the code is instead interpreted as assigning the value red>[[User:Example|Example]]</font> to the named parameter <font color. To prevent this, the value must be passed to a named parameter. So {{TEx2|1=<font color=red>[[User:Example|Example]]</font>}} will work correctly (producing Template:TEx2).

It is sometimes easier to replace the equals sign with its HTML equivalent (&#x3d;), which renders as =. However this will not work if the equals sign is involved in another template call or HTML tag: <font color&#x3d;red>[[User:Example|Example]]</font> will display as Example.

Pipe character[edit | edit source]

The pipe character cannot appear in a parameter value unless it is a part of:

  1. Another template call
  2. A piped link
  3. An image tag

This means that parameter values cannot contain raw wikitable code. However, the template {{!}} has been provided on most Wikis; this template contains only the raw pipe character, so it can be used in table code. It is also possible to use the HTML pipe character (&#124;) unless the pipe is 'functional':

If you type Where Template:TEx4 contains You get
{{TEx4|
{|
|-
| A || B
|-
| C || D
|} <nowiki>}}
[[:Template:TEx4]] Template:TEx4
{{TEx4|
{{{!}}
{{!-}}
{{!}} A {{!!}} B
{{!-}}
{{!}} C {{!!}} D
{{!}}} }}
A B
C D
{{TEx4|

{&#124; &#124;- &#124;&#124; A &#124;&#124; B &#124;- &#124;&#124; C &#124;&#124; D &#124;} }}

Template:TEx4

Braces and brackets[edit | edit source]

A parameter value cannot contain unmatched double brace characters {{ or }} or square brackets [[ or ]]. A parameter value can contain matched sets of braces, so template calls, parser functions, or other parameters can be included:

If you type Where Template:TEx2 contains You get
{{TEx2|PQR}STU}} [[:Template:TEx2]] Template:TEx2
{{TEx2|PQR}}STU}} Template:TEx2STU
{{TEx2|PQR{STU}} Template:TEx2
{{TEx2|PQR{{STU}} Template:TEx2

Note that in the final example, the template call is not closed, probably resulting in unexpected formatting and/or template display. While matched sets of braces usually do not create a problem, care must be taken when large numbers of braces are nested together. Matched sets of braces are evaluated from the inside working outwards; if possible, the innermost three braces are interpreted as enclosing a parameter value, if there is a matching set of three braces to close the parameter. If this is not possible, then the innermost two braces are interpreted as enclosing a template call or parser function. Some examples:

  • Matched sets of four consecutive braces are interpreted as a parameter surrounded by single braces: {{{{foo}}}} is equivalent to { {{{foo}}} }.
  • Unmatched sets of four braces are interpreted as nested template calls: {{{{TEx1}} }} is parsed as a call to a template, the name of which is dependent on the output of TEx1. In this example, {{{{TEx1}} }} results in {{Template:TEx1 }}, as the Hello world! template does not exist.
  • Matched sets of five consecutive braces are interpreted as a template call surrounding a parameter: {{{{{foo}}}}} is equivalent to {{ {{{foo}}} }}.
  • Unmatched sets of five braces are interpreted using the standard rules: {{{{{TEx1}} }}} is interpreted as a named parameter with the name dependent on the result of Template:TEx1, which in this case is equivalent to {{{Hello world!}}}.

In general, if unexpected results are obtained when using large numbers of nested braces, consider separating them into the correct groups of pairs and triplets using spaces. This will usually not have any adverse consequences.

XML[edit | edit source]

Parameters are not expanded when called from inside XML-style tags. This is a restriction not so much on what values can be passed to a parameter as to where those parameters can be used within the code in the template. This is most commonly encountered with the <ref></ref> tags that are provided by cite.php, and are the most popular citation form on many Wikis.

If you type Where Template:TEx5 contains You get
{{TEx5|ABC|DEF}} <ref name={{{1}}}>{{TEx1}} {{{2}}}</ref> Template:TEx5
{{TEx5|GHI|JKL}} Template:TEx5
References produced


Note that while both the references appear to be correctly formatted, neither parameter has expanded correctly. Both references have the 'name' attribute .7B.7B.7B1.7D.7D.7D, which is the HTML equivalent to {{{1}}}. The second parameter error is a quirk of the cite extension which does not like receiving entire references from inside templates. There are several other bugs associated with <ref></ref> tags, some of which can be found at the Mediawiki documentation page.

This bug applies only to XML-style tags provided by MediaWiki extensions, not to basic HTML. Using the code <font color={{{1}}}> in a template will still display correctly, while tags like <source> and <imagemap> will be affected. You can use the ParserFunction #tag: to circumvent this problem.

Default parameters[edit | edit source]

See also: Help:Parameter default

If a parameter is included in the template code, but is not defined in the template call, then it is not replaced when the template is transcluded, as shown in the last two examples above. To avoid this, default parameters can be specified. Default parameters are placed within the triple braces, after a pipe character, and can be another parameter:

If you type Where Template:TEx6 contains You get
{{TEx6|A|x=B}} [[:Template:TEx6]] Template:TEx6
{{TEx6}} Template:TEx6
{{TEx6|A|x=B|y=C}} Template:TEx6
{{TEx6||y=C}} Template:TEx6

Note that the default value is only called if the parameter is undefined, not just empty. Passing 'null' to a parameter, as in the fourth example above, still results in the parameter being defined. This may or may not be desirable: if not, the ParserFunction #if: is a more rigorous test for a parameter's content.

There are no restrictions on default values other than those mentioned above which apply to normal parameter values.

Code on template pages[edit | edit source]

Template pages are in all respects identical to other Wiki pages - the same formatting will work in the same manner as it will anywhere else. However there are few pieces of wikimarkup which are designed primarily for use on template pages.

<noinclude>[edit | edit source]

Any code placed between the XML tags <noinclude> and </noinclude> will not be included when a template is transcluded:

If you type Where Template:TEx7 contains You get
{{TEx7}} [[:Template:TEx7]] Template:TEx7

<noinclude></noinclude> tags are most commonly used to include documentation or notes about a template on the template page, which will not appear when the template is transcluded. They may also be used to encapsulate a category tag, to enable the template page itself to be included in the category without also categorising every page the template is transcluded in.

<includeonly>[edit | edit source]

Any code placed between the XML tags <includeonly> and </includeonly> will, as the name suggests, only be rendered when the template is transcluded. Any code placed between the tags will not appear or be parsed when the template page itself is displayed.

If you type Where Template:TEx8 contains You get
{{TEx8}} [[:Template:TEx8]] Template:TEx8

<includeonly></includeonly> tags are often used to encapsulate category tags, to enable all pages on which the template is transcluded to be categorised, while the template itself is not. If the template code renders very messily when no parameters are specified, the entire template code can be encapsulated in <includeonly></includeonly> tags to prevent messy display.

<onlyinclude>[edit | edit source]

Any code placed between the XML tags <onlyinclude></onlyinclude> is rendered normally when the template page itself is viewed. However, when the template is transcluded, only code encapsulated by <onlyinclude> tags will be included.

If you type Where Template:TEx9 contains You get
{{TEx9}} [[:Template:TEx9]] Template:TEx9

Transclusion[edit | edit source]

A template can call another template without difficulty:

If you type Where Template:TEx10 contains You get
{{TEx10|abc|def}} [[:Template:TEx10]] Template:TEx10

The set of parameter expressions are not automatically "passed through" the outer template to the inner template. However, it is easy to manually pass parameters through a template:

If you type Where Template:TEx11 contains You get
{{TEx11|ABC|x=DEF}} [[:Template:TEx11]] Template:TEx11

A template is permitted to transclude itself. However, the parser incldues protection against an infinite loop. When the template is transcluded for the second time, the template call within the template is replaced by a link to the template rather than a transclusion.

If you type Where Template:TEx12 contains You get
{{TEx12|abc|def}} [[:Template:TEx12]] Template:TEx12

Parsing templates[edit | edit source]

When the MediaWiki parser encounters a template (defined as a matched pair of braces not inside <nowiki> tags), the template is expanded using the following algorithm:

  1. The template call is divided into the template name and parameter expressions, by looking for pipe characters. Pipes contained within matched double braces or square brackets are ignored.
    • This division is performed purely based on pipe characters currently present in the template call, ignoring those potentially contained within templates. This is what permits the use of Template:!.
    • A potentially interesting feature is that characters including and following a hash # are stripped from the template name after this division. So {{TEx4#def|ABC}} will be parsed in exactly the same way as {{TEx4|ABC}}.
  2. The wikicode for the template name is evaluated, calling the template parser recursively if necessary.
  3. The wikicode for each parameter expression is evaluated, again using recursion if the wikicode contains another template.
  4. Any parameter expression now containing a raw equals sign is split around that equals sign into a parameter name and parameter value. If a parameter expression contains more than one equals sign, the division is done around the first (working left to right).
  5. Any remaining parameter expressions which do not contain equals signs are assigned as values to the implicit parameters, working left to right. So the first parameter expression which does not contain an equals sign is assigned as the value of parameter 1, the next parameter expression is assigned as the value of parameter 2, etc.
  6. The wikicode of the template page is analysed and stripped around <noinclude>, <includeonly> or <onlyinclude> tags, if present.
  7. The template call is replaced by the analysed wikicode, replacing parameters by their values if possible.
    • Any parameters that do not appear in the analysed wikicode are discarded, and any parameters appearing in the wikicode which have not been assigned a value are replaced by their defaults (if defined) or left as they are.

Stripping and tidying[edit | edit source]

The MediaWiki parser strips whitespace from before and after named parameters, but not always from around unnamed parameters. Whitespace is also stripped from before and after the template name and parameter names:

If you type Where Template:TEx3 contains You get
{{TEx3|A|B|C}} [[:Template:TEx3]] Template:TEx3
{{ TEx3 | A | B | C | x = C }} Template:TEx3

The template name is also stripped at a hash character (#) if one is present:

If you type Where Template:TEx2 contains You get
{{TEx2|def}} [[:Template:TEx2]] Template:TEx2
{{TEx2#pqr|def}} Template:TEx2

Even though Template:TEx2 does not contain a section entitled "pqr". This feature is the basis of the on the english wikipedia, which checks for a leading hash on a parameter. The template contains the following code:

{{#ifexist:Template:Hif{{{test|defaultNoHash}}}|{{{then|1}}}|{{{else|0}}}}}

If the parameter "test" begins with a hash, then the parser function #ifexist: (which also strips around hash characters) will be checking the existence of Template:Hif, returning true. If, however, the parameter "test" does not begin with a hash, then the parser function receives some other template name to check, returning false.

Special:ExpandTemplates[edit | edit source]

On wikis with the ExpandTemplates extension, you can use Special:ExpandTemplates to see the output of the template parsing process for a particular page or piece of template code. The extension expands the code using the MediaWiki parser, expanding templates, parser functions and variables to raw wikicode.

Miscellaneous template issues[edit | edit source]

Wikimarkup[edit | edit source]

If the first character of a template page is ;, :, * or #, then when the template is parsed, an HTML line break <br/> is inserted immediately before the start of the template code. This ensures that these characters are at the beginning of a line, resulting in an indentation, bulleted or numbered list, etc. If this effect is not desired, use the HTML equivalents (such as &#58; for a colon) or surround the first character with <nowiki></nowiki> tags.

Redirects[edit | edit source]

If a transcluded page is a redirect to another page, then the wikicode of the target page is transcluded instead. A double redirect does not work. Transcluding the target page onto the redirect page has a similar effect, but care must be taken to ensure that any named or unnamed parameter values are "passed through" to the target page - it is usually more convenient to use a redirect. Careful use of redirects permits a certain degree of recursion:

If you type Where Template:TEx13a contains You get
{{TEx13a}} [[:Template:TEx13a]] Template:TEx13a

Where Template:TEx13b is a redirect to Template:TEx13a.

msgnw[edit | edit source]

An abbreviation for "message, nowiki", msgnw:, like subst:, is a prefix which can be added to template calls to affect their display. When a template call including the msgnw prefix is encountered, it is simply replaced by the complete wikitext of the template page, surrounded by <nowiki> tags. Parameters are not replaced by their values, and the text is not stripped around <noinclude> or <includeonly> tags.

If you type Where Template:TEx3 contains You get
{{msgnw:TEx3}} [[:Template:TEx3]] [[:Template:TEx3]]
{{msgnw:TEx3|A|B|C}} [[:Template:TEx3]]
{{msgnw:TEx3|1=A|x=B|y=C}} [[:Template:TEx3]]

Old revisions[edit | edit source]

When viewing an old version of a page which transcludes templates, the current version of those templates is used to render the page, even if the templates have been modified in the intervening time. Consequently, old versions transcluding templates may not look exactly as they did when the revision was made.

If the FlaggedRevisions extension is installed on your wiki, it may have been configured to display the stable versions of templates when rendering pages. This means that, if a template is edited but is not marked as sighted, pages transcluding that template will still display the previous, sighted, revision of the template. Old versions of pages will still use the most recent sighted version of the template, even if that was not the version of the template that was in use at the time the revision was created.

History of templates on MediaWiki[edit | edit source]

MediaWiki 1.2.6

Pages in the MediaWiki namespace only could be transcluded with the code {{msg:templatename}}, to transclude the page MediaWiki:templatename. Parameters were not supported.

MediaWiki 1.3

Pages from all namespaces could be transcluded, with the msg: prefix now optional. Named and unnamed parameters were supported, but default values were not. An undefined parameter was interpreted as a template call surrounded by single braces, almost inevitably resulting in redlinks in the final render. Default values could be improvised by storing them as the wikitext of Template:parametername.

MediaWiki 1.4

Templates could be transcluded more than five times on the same page (previously this was not possible).

MediaWiki 1.5

No fundamental changes were made to the template mechanism itself, but the expansion of the collection of magic words enabled greater flexibility in the use of templates.

MediaWiki 1.6

More magic words were added, and the current parameter default mechanism was implemented. <noinclude>, <includeonly> and <onlyinclude> were also implemented.