Help:Template messages

From The Urban Dead Wiki
Jump to navigationJump to search

The (whole) contents of one page can be placed onto another page via a process called transclusion. If a page is specially intended for this purpose it is called a template.

This can be considered a wiki subroutine facility and is comparable to an #include statement or macro that is expanded at page view time. Substitution allows templates to be used as a macro facility.

This page and its extension Help:Advanced templates provide a reference manual on templates in MediaWiki. For an introduction, see A quick guide to templates and mw:Help:Templates. For syntax often used within templates, see Help:ParserFunctions and other "Advanced functioning" help pages listed below.


General

The template namespace is the namespace with prefix "Template:"

A page in this namespace is called a template. The contents of such a page (either fixed or depending on parameters and/or variables) is designed to be useful for insertion in other pages (transclusion, creating a compound document). In a what links here list, the term in MediaWiki:Istemplate is used, by default "inclusion", sometimes "transclusion", currently on this wiki "transclusion".

The syntax for insertion of the page "Template:name" is {{name}}. This is called a template tag, and comprises two instances of the "brace" at either side of the template page name, excluding the "Template:" prefix.

Example: abc{{tc}}def

(using Template:tc containing "Template:Tc")

Gives: abcTemplate:Tcdef.

This reference in the wikitext causes insertion of the template content when the referring page is rendered. Various equivalent terms are:

  • inclusion / including the page - "inclusion" by itself may be ambiguous, since one can say that a section etc. is included in a page even if there is no transclusion; based on these terms are the tag names "noinclude" and "includeonly", see below
  • transclusion / transcluding the page - this is more specific than "inclusion"
  • page embedding / embedding the page

Terms too general to be used with "page", therefore only used with "template":

  • template call / calling the template - referring more to the template tag than to the result
  • template use / using the template

Depending on context "including" can be used as opposed to substituting the template.

To create a hyperlink to a template page, use the usual wikilink syntax [[Template:name]].

The pages in the namespaces other from "Template" namespace can also be used as templates, except pages in namespaces specified in $wgNonincludableNamespaces. To use a page in the main namespace as a template, add a colon before the page name.

Also it provides an alternative way of calling a template, which can be used in the case of a name conflict with a variable, e.g. Template:Ns:3 and Template:PAGENAME; while {{Ns:3}} and {{PAGENAME}} give User talk and Template messages, {{:Template:Ns:3}} and {{:Template:PAGENAME}} give Template:Ns:3 and Template:PAGENAME.

Using a page outside the template namespace as template can be useful for:

  • quoting interface messages in the MediaWiki namespace
  • templates for personal use in subpages of one's userpage, e.g. for experimenting
  • inclusion of pages in other pages in the same namespace, e.g. having an extra page associated with each page, such as a to-do list, with a simple name correspondence; it can be created and included with {{{{NAMESPACE}}:{{PAGENAME}}/todo}}

Even if a template is intended for use on talk pages, the template page can better not be put in a talk namespace, because then there is no page for discussing it. If it is for general use it is often put as usual in the template namespace, see e.g. Wikipedia:Talk page templates and Wikipedia:Template messages/User talk namespace. An auxiliary template for personal use for a user talk page can best be put in a subpage of the user page, not one of the user talk page, for example "User:Abc/Talk intro" rather than "User talk:Abc/Intro"; this allows discussion of the template at "User talk:Abc/Talk intro".

As usual the template name is case sensitive except (on most projects) for the first letter, and a blank space is equivalent with an underscore (as opposed to parameter names, see below: they are case-sensitive, even with respect to the first letter, and spaces are distinguished from underscores).

If the page to be transcluded does not exist, then a link to the edit page is produced (for conversion details see Template:Exists). Thus, one way of making a template is putting the tag first, and then following the link. An exception is that transclusion of a "non-existing" page in the MediaWiki namespace trancludes the default content of that page. In other words, apart from transcluding a page one can also transclude a system message in a specified language (by default the site language); the result is independent of the user-specified interface language.

One can call a template that calls another template. If a template calls itself directly or indirectly, inclusion works only on one level for each template. However, with templates redirecting to the template that one would want to call recursively, one can achieve recursion without having to make copies of the whole template content, with the number of levels limited by the number of redirects. See also Repetition within a page and Template:Links-small.

A variable in a template is evaluated after insertion in the referring page, i.e. if {{PAGENAME}} occurs in the wikitext of a template, it is rendered as the name of the referring page, not the name of the template.

A list of pages embedded in a page (as recorded in the templatelinks table), all with links, is given on the edit page. Notes:

  • on a section edit page first the whole list is given, i.e. also the templates used in other sections; after pressing preview only those in the section, updated for the edits made, if any; preview on first edit gives the full list;
  • similarly, when editing an old version of a page, the list is first given for the current version, while after pressing preview the templates that used to be included are shown, updated for the edits on the old version made in the current session, if any;
  • if a page is conditionally embedded through #if, #ifeq, #ifexist, #ifexpr, or #switch, it is counted as embedded, even if the condition is not fulfilled
  • if the name of an embedded page is an expression, e.g. {{abc{{CURRENTDAY}}}}, currently giving Template:Abc21, or {{{{#ifexist:Template:A|A|x1}}|Template does not exist}}, currently giving {{{{#ifexist:Template:A|A|x1}}|Template does not exist}}, the current template name is shown.

Thus, to use "What links here" to find the pages that actually embed template A, instead of using e.g.

{{#if:..|{{a|pa1}}|{{b|pb1}}}}

one has to use an alternative, e.g., duplicating the condition:

{{{{#if:..|a|b}}|{{#if:..|pa1|pb1}}}}

or, using Template:Links-small:

{{{{#if:..|a|echo}}|1=pa1|echo={{b|pb1}}}}

Only with the first of the two alternatives "What links here" also finds the pages that actually embed template B. In the second alternative the page is always considered embedded. If we replace "b" by "{{if:1|b}}" the page is never considered embedded.

(Supported in version 1.4 and higher.)

When saving a page without newline at the end, and going to the edit page again, there is a newline at the end. However, this does not seem to have effect, see the example above and the following example:

{{Numbered list demo}}{{Numbered list demo}}
{{Numbered list demo}}

that uses Template:Numbered list demo three times, gives

Template:Numbered list demo Template:Numbered list demo Template:Numbered list demo

In a template name the character "#" and any characters after that are ignored: "{{tc#abc}}" gives "Template:Tc". This is used in Template:Links-small.

A wikitext with consecutive double opening braces and consecutive double closing braces is interpreted as containing a template parameter tag with triple braces. To avoid that, use a space in at least one of the two quadruples. For example, "{{{{tc}}}}" gives "{{{{tc}}}}", while "{{ {{tc}}}}" gives "{{ Template:Tc}}".

With Special:ExpandTemplates one can view the expanded wikitext a template call produces, as intermediate step toward rendering. The same is also produced with a URL like //wiki.urbandead.com/index.php?title=Help:Template_messages&action=raw&templates=expand.

Use of templates across projects

A template only works when referred to from a page in the same project. To use it in another project, one has to copy it to there. Wikipedia:Bugzilla:1126 is a request to lift that restriction, i.e. allow interwiki use of templates.

The adjustments needed in the copy, to work on the other project, can be reduced by using {{SERVER}}, localurl, and generic namespace names, and writing links in a way that works on multiple projects, e.g. Help:Table. For copying multiple templates, export and import can be helpful. It is also convenient if the template names can be the same on the other project. Therefore, when choosing template names, check which names are in use on other projects to which people might want to copy the templates. Note that if a template is referred to by something like abc{{NAMESPACE}}, a project with different namespace names requires a different template name, or a redirect.

Transclusion across projects, hence changing contents from a central place, is only possible:

  • for content in the form of an image on Commons, to any page,
  • for editable content on an image page on Commons, including content transcluded from other pages on Commons, to the corresponding local image pages, if there is no local image with the same name


Sometimes multiple projects require pages which are partly the same and partly different. For example, on some projects "m:" is used as interwiki link to Meta, and on some projects "MetaWikipedia:". In this case a common wikitext can be used, calling project-specific templates. In the example the wikitext of the page could contain {{meta}}, and we would have on each wiki a Template:Meta containing the required prefix.

Parameters

Template parameters are called-by-value, and therefore input parameters only (see also the section "Template expansion" below). They are either named or implicitly numbered 1, 2, 3, ...

Comparison between named or implicitly numbered parameters:

  • With implicit numbering the call is shorter
  • Named parameters can be specified in any order.
  • If a parameter value contains "=" the name has to be put explicitly, even if it is a number (see also below).
  • Spaces and newlines are stripped from the start and end of parameter values of named parameters, but not of implicitly numbered parameters

In the template definition, the formal parameter (the placeholder for the parameter value) is a parameter name with three pairs of braces. So, for example, you would write {{{myVariableName}}} for a template parameter which you wanted to call myVariableName.


MediaWiki version: 1.6 (for parameters defaults)

In the template call, the syntax is either

  • {{templatename|parname1=parvalue1|parname2=parvalue2}} with tags {{{parname1|default}}}, {{{parname2|default}}}, etc. in the template, or
  • {{templatename|parvalue1|parvalue2}} with tags {{{1|default}}}, {{{2|default}}}, etc. in the template.

The default (optional, together with the pipe character in front) can be different for every occurrence, and applies if no value is specified when calling the template, not to be confused with the case that the empty value is specified.

To distinguish between a parameter being defined and non-empty on one hand, or undefined or empty on the other hand, use {{if}} with a blank default:

{{if| {{{param|}}} | param is defined and non-empty | param is undefined or empty}}.

To distinguish between defined (and possibly empty) and undefined, use:

{{ifeq| {{{param|+}}} | {{{param|-}}} | param is defined | param is undefined }}.

In the case of page substitution with an undefined parameter, not the default but the parameter itself with default is substituted into the wikitext. If this is not desired, see Help:Substitution#Parameter_default_considerations for an alternative (it also uses the {{ifeq}} just mentioned).

Monitoring parameter usage

To monitor the usage of a parameter of a template (in the case that many pages use the template), this template can call an auxiliary template of which the name depends on whether the parameter is defined. The possible auxiliary templates need not exist, if they are e.g. used as parameter value of Template:Tim, to avoid displaying anything. Applying "What links here" to the possible auxiliary templates shows which pages use the template with the parameter, and which pages use the template without the parameter. This parameter usage monitor facility should preferably be built into the template when creating the template or introducing a new parameter. If it is done afterwards "What links here" may not show a page until it has been refreshed by an ordinary or dummy edit or purge.

Applications of monitoring parameter usage include:

  • check where the parameter has not yet been specified, in order to add it
  • check where a parameter is used that is renamed, in order to change the template calls
  • check whether a parameter is used before abolishing it
  • when a template has been changed with respect to processing a particular parameter, check the pages which use the parameter (or some of them) to see if things work as desired.

In a similar way an auxiliary template can be called for a "template / parameter / parameter value" combination or "template / parameter / parameter value range" combination. "What links here" then shows which pages use the template with this parameter value, or with the parameter in the given range.

See Template:Tim.

Example: named parameter substitution

Let's create a template called Name-example (that is, the template will be Template:Name-example), with a parameter for the first name which we will call firstName, and a parameter for the last name which we will call lastName.

Type the following in the new Template:Name-example:

:I am a template example, my first name is '''{{{firstName}}}''' and my last name is '''{{{lastName}}}'''.
:
:You can reference my page at [[{{{lastName}}}, {{{firstName}}}]].

On a second page, type this: {{Name-example}}

The result is: Template:Name-example

Because the template has no parameters.

But if we type this on the second page: {{Name-example | firstName=John | lastName=Smith}}

The result will looks like this:
Template:Name-example

To analyse the working, one can apply Special:ExpandTemplates to see the expanded wikitext as intermediate result:

:I am a template example, my first name is '''John''' and my last name is '''Smith'''.
:
:You can reference my page at [[Smith, John]].

When this wikitext is applied directly the resulting rendering is the same.

Example: numeric parameter substitution

An example of how the contents of a parameter function.

The simplest case

Let us first define a template with the name t0, which will

  • expect a single argument
  • give back the text of that argument, with no spaces before or after it, between "start-" and "-end":
start-{{{1}}}-end

the definition of course being on page Template:t0.

  1. Calling the template named t0 with a parameter value of "a", i.e.,
    {{t0|a}}
    gives
    "Template:T0"
  2. Calling the template named t0 with a parameter value of " " (a blank space), i.e.,
    {{t0| }}
    gives
    "Template:T0" .
  3. Calling the template named t0 with a parameter value of "" (an empty string), i.e.,
    {{t0|}}
    gives
    "Template:T0".
  4. Calling the template named t0 and not passing any parameters, i.e.,
    {{t0}}
    gives
    "Template:T0".

If something like {{{1}}} or in fact any {{{name}}} is visible on an ordinary page it typically indicates that a mandatory parameter of a template used on this page isn't defined.

Stripping of spaces and newlines

Calling the template named t0 with a parameter which consists of some spaces or two newlines:

{{t0|     }}

gives

Template:T0
{{t0|

}}

gives

Template:T0
{{t0|1=     }}

gives

Template:T0
{{t0|1=

}}

gives

Template:T0

Thus, spaces and newlines are stripped from the start and end of parameter values of named parameters, but not of unnamed parameters! This is probably a bug. See Help:Newlines and spaces. Also, compare conditional whitespace.

Declaring a default value

Main article: Help:Parameter default.

Now let us define a similar template with the name t which contains a single numbered parameter 1 with a default of pqr. The only difference between the effects of t and t0 appears when they are called with no parameter (and no "|"):

start-{{{1|pqr}}}-end

the definition of course being on page Template:t.

  1. Calling the template named t with a parameter value of "a", i.e.,
    {{t|a}}
    gives
    "{{{2}}}".
  2. Calling the template named t with a parameter value of " ", i.e.,
    {{t| }}
    gives
    "{{{2}}}".
  3. Calling the template named t with a parameter value of "", i.e.,
    {{t|}}
    gives
    "{{{2}}}".
  4. Calling the template named t with named parameter 1=, i.e.,
    {{t|1=no surprise}}
    gives
    "{{{2}}}".
  5. Calling the template named t with 1= after an unnamed parameter, i.e.,
    {{t|no|1=surprise}}
    gives
    "{{{2}}}".
  6. Calling the template named t with 1= before an unnamed parameter, i.e.,
    {{t|1=no|surprise}}
    gives
    "{{{2}}}".
  7. Calling the template named t and no parameter at all, i.e.,
    {{t}}
    gives
    "{{{2}}}".
  8. Calling the template named t and no named or unnamed parameter 1, i.e.,
    {{t|2=two}}
    gives
    "two".

Restrictions on parameter values

  • If a parameter value contains an equals sign, the parameter name must be put in explicitly, even when it is 1, 2, 3, etc. (Alternately, the equals sign could be replaced by the HTML entity =)
  • Any unmatched pairs of two consecutive braces or brackets must be placed in nowiki tags. Braces can be used for nested template parameters, nested templates or parser functions while brackets can be used for links. Unmatched pairs not placed in nowiki tags either prevent template expansion or are taken as closing braces for the template call.
    • For example, using Template:Timc:
    • {{tlis|abc]]def[[ghi}} gives {{tlis|abc]]def[[ghi}} rather than aabc]]def[[ghib (the template is not expanded; see also [1] where this example causes several sections not to be displayed).
    • {{tlis|abc}}def}} gives Template:Tlisdef}} rather than aabc}}defb (the first closing braces are taken as those for the template call).
  • The expression for a parameter value cannot contain the variable localurl with query string, due to the pipe character.

A parameter value containing a pipe character

To define a parameter value containing a pipe character (|) which is not part of a template call, parser function call, piped link or image tag, use Template:! containing "|". Using Template:Tcw, compare {{t0|a{{!}}b}} giving Template:T0, {{t0|a|b}} giving Template:T0 and {{t0|a|b}} giving Template:T0. The difference between the first and the second is that in the first case the expanded wikitext is start-a|b-end, while in the second case it is start-a|b-end. This is rendered the same in final output but makes a difference when used in table syntax: this requires the "real" pipe character.

Using Template:Tcw,

{{x2|{{{!}} 
{{!}} A 
{{!}} B
{{!}}- 
{{!}} C
{{!}} D
{{!}}}
}}

gives

Template:X2

while

{{x2|{| 
| A 
| B
|- 
| C
| D
|}

}}

gives

Template:X2

and

{{x2|{| 
| A 
| B
|- 
| C
| D
|}
}}

gives

Template:X2

Similar constructs can allow a parameter value to contain a double closing brace. Even a parameter name can contain "|" and "}}" in this way, but that seems of little use. However, a pagename cannot contain "|" or a brace.

Equals sign in parameter value

When a parameter value contains an equals sign, the parameter name must be stated explicitly, otherwise the part of the parameter value before the equals sign is taken as the parameter name. If that happens accidentally, this parameter is likely to be unused, hence harmless, but the intended implicit parameter 1, 2, or 3, etc., gets no value.

Example: {{TTT|a=b|c}} (using Template:TTT containing "Template:TTT") gives Template:TTT (unused parameter a is assigned the value b, the first parameter value for which no parameter name is specified is assigned to the parameter with the implicit name "1" — it reads like so: Use template TTT, assign "b" to the parameter "a", use the value "c" for your first implicit parameter {{{1}}}.), while {{TTT|1=a=b|2=c}} gives Template:TTT (the first parameter is assigned the value "a=b" — it reads like so: Use template TTT, assign "a=b" to the expressed parameter "1", assign "c" to the expressed parameter "2"). {{TTT|1=a=b|2=c|d}} gives Template:TTT, "d" is assigned to "1" as first implicit parameter, overwriting the value "a=b".

A parameter definition (between pipe characters or a pipe character and template end tags) may depend on a template, parser function, variable, or template parameter. The explicit or implicit name of the parameter is determined after expansion. For example, a template call {{t2|{{{a}}}}} assigns the value of {{{a}}} to implicit parameter 1 if that value does not contain an equals sign, but if it has the value "b=c", c is assigned to b. If we anyway want to assign the value of {{{a}}} to 1 we have to use an explicit parameter 1: {{t2|1={{{a}}}}}.

Compare:

Similarly, parameter definition {{{a}}}=b where {{{a}}} has value "c=d" results in "d=b" being assigned to c, for example:

Note that even "style=.." inside < > brackets is affected, i.e., the parsing process ignores these brackets.

Subsequent parameters

If a parameter name is made explicit because the parameter value contains (or may contain) an equals sign, this affects the implicit numbers of subsequent parameters too: implicit numbering does not skip numbers which are already used for explicit parameters. One remedy is to make these subsequent parameters explicit too, but one can also compensate for the shift by assigning a dummy value to the unnamed parameter before assigning the real value to the same parameter in explicit form.

For example, Template:Links-small contains "=". Therefore, if the parameters have to be "a {{mlw|b}} c" and "d":

If the parameters have to be "d" and "a {{mlw|b}} c":

Mix of named and unnamed parameters

In the case of a mix of named and unnamed parameters in a template tag, the unnamed parameters are numbered 1,2,3,.., so they are not numbered according to the position in the mixed list as a whole.

For example, {{t sup|3=1|2|1=3|4|5|6|7}} using Template:Tcw gives Template:T sup.

When parameters do not expand

MediaWiki version: 1.6 (for parameters defaults)

Parameters do not get expanded when they are inside nowiki tags or XML-style extension tags. Thus, the following will not work within a template, because the parameter is not expanded:

 <myextension xparam={{{tparam}}}> ... </myextension>
 

More than three opening braces

In the case of more than three opening braces the last three are interpreted as parameter braces. If there is no matching triple of closing braces the last two opening braces are taken as braces for a template or parser function.

Thus {{{{a}}}} is parsed as { {{{a}}} }, e.g. {{{{t1|1}}}} gives "{1}", while {{ {{t1|1}}}} gives {{ Template:T1}} and {{{{t1|1}} }} gives also {{Template:T1 }}. Interestingly {{{{t1|1}} }} {{{5}}} gives {{Template:T1 }} {{{5}}}.

Furthermore, {{{{{a}}}}} is parsed as {{ {{{a}}} }}, e.g. {{{{{abc|tc}}}}} gives "Template:Tc".

Thus if an expression for a parameter name starts with a template or parser function a blank space is needed after the third brace, e.g. {{{ {{#if:x|tc|ab}}}}} gives the value of {{{ {{#if:x|tc|ab}}}}}, while {{{{{#if:x|tc|ab}}}}} gives "Template:Tc" (using the default value tc of parameter #if:x, and ignoring "|ab").

With 6 braces, e.g. {{{{{{a|b}}}|c}}} gives c.

Template mechanism

The template mechanism involves the following steps:

  • The pipe characters in template calls determine the separation into template name and parameter definitions. This separation does not depend on possible pipe characters in the expanded form of the text between the opening and closing braces of the template. For example, {{ {{t6}} }} using Template:Tcw gives {{ Template:T6 }}, not the result of {{ t2demo|a }} which is Template:T2demo. This is because "t2demo|a" is not a valid template name (not to be confused with a template with a valid name that does not exist), so the template call is not expanded.
Note that in this case partial or successive substitution does not give the same result as without substitution: {{ {{subst:t6}} }} gives the wikitext {{ t2demo|a }}, rendered as Template:T2demo.
  • The template name and each of the parameter definitions is evaluated. The leftmost equals sign, if any, in each parameter definition separates the parameter name from the parameter value.
  • The values are assigned to the parameters from left to right (the result can not be directly viewed), meaning that a named or numbered parameter may be specified several times, the last one being the actual value that will be kept when passing the parameter during the final instantiation of the template below.
  • Template calls are replaced by template content, where the parameter tags with matching names are replaced by their values or defaults (the result of this step can be viewed by applying subst either again, or directly to the template and the variables).

The process is applied recursively until there are no more template calls to replace.

All whitespaces before and after a parameter value are ignored if "=" is used.

"{{t|1= a}}" gives "{{{2}}}".
"{{t|1=a }}" gives "{{{2}}}".
"{{t| a}}" gives "{{{2}}}".
"{{t|a }}" gives "{{{2}}}".

A parameter value can contain a piped link; the "|" in such a link is not taken as parameter separator.

Example: "{{t|[[a|b]]}}" gives "{{{2}}}".
Example: "{{t|[[a|b]] }}" gives "{{{2}}}".

(In this case the space has effect.)

On rendering, surplus parameter values (including named parameters that do not occur in the template) are ignored: {{t|a|b}} gives b.

Parameters without names (i.e. that don't contain an equal sign) are numbered implicitly starting by 1, from left to right.

Example: "{{t|a|b|c}}" is equivalent to "{{t|1=a|2=b|3=c}}"

Numbered parameters can also be skipped or can be specified in alternate order by numbering them explicitly.

Example: "{{t|3=c|2=b|1=a}}" is equivalent to "{{t|1=a|2=b|3=c}}"
Example: "{{t|a|b|c|10=j}}" is equivalent to "{{t|1=a|2=b|3=c|10=j}}"

This also makes it possible to apply a default value for parameter 1, while specifying a value for parameter 2:

{{t2d|2=a}}, using Template:Timc, gives Template:T2d.

Template calls can contain multiple occurrences of the same named parameter, and a numbered parameter can be specified multiple times by using its number explicitly. The effective value of parameters is the value of the last occurrence (from left to right) of the parameter with the same name, once the parameter names have been evaluated.

Example: "{{t|a|b|c|2=B}}" is equivalent to "{{t|a|B|c}}"

The final list of formal parameters before the template itself is instantiated is then unordered because the list is indexed by the evaluated parameter named (this list is an associative array).

When ParserFunctions were not available yet, multiple assignments of parameters with the same name (and thus allowing parameter overrides) were ingeniously used to perform branching, e.g. in the now deleted en:Template:If defined.

See also Help:Parameter default.

Template tag lay-out

To have a desired template tag lay-out, especially in the case of many parameters, additional dummy parameters can be used with a newline, spaces, and/or comments. In the case of unnamed parameters, this means that some parameter numbers are not used in the template content, so that their values, present in the template tag, do not affect the rendering of the template. For example, using Template:Tcw,

{{t3d |a|b|c| 1
      |d|e|f| 2
      |g|h|i| 3
}}

gives:

Template:T3d

If parameters are named, dummy parameters can easily be inserted at any time. If they are unnamed, then, to avoid renumbering, one can insert named parameters: any text including an equals sign will do, if the text on the left is not one of the parameter numbers: this text is interpreted as the name of an unused parameter, hence ignored.

Example:

Using Template:Links-small

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

|30}}

which gives

8 rd nd bd qd kd bd nd rd
7 File:Chess d40.png pd pd pd pd pd pd pd
6 pd File:Chess d40.png File:Chess l40.png File:Chess d40.png File:Chess l40.png File:Chess d40.png File:Chess l40.png File:Chess d40.png
5 File:Chess d40.png File:Chess l40.png File:Chess d40.png File:Chess l40.png File:Chess d40.png File:Chess l40.png File:Chess d40.png File:Chess l40.png
4 File:Chess l40.png pl File:Chess l40.png File:Chess d40.png File:Chess l40.png File:Chess d40.png pl File:Chess d40.png
3 File:Chess d40.png File:Chess l40.png File:Chess d40.png File:Chess l40.png File:Chess d40.png File:Chess l40.png File:Chess d40.png bl
2 pl File:Chess d40.png pl pl pl pl File:Chess l40.png pl
1 rl nl bl ql kl File:Chess l40.png nl rl
a b c d e f g h

In this example, the 1 to 8 row numbers and a to h column numbers (as well as their surrounding spaces and newlines) in the parameter list are hidden within a dummy parameter (with an empty name before the equal sign).

The template generates a HTML table where each cell contains an image whose name is dynamically generated from the 64 first automatically numbered parameters (there are intermediate parameters within the numbered list, but as these dummy parameters are named explicitly, they don't increment the parameter number used to generate default parameter names. So the parameter with autogenerated name "1" effectively contains the "rd" value).

The template is then called with a parameter list that contains:

  • 65 parameters automatically named from "1" to "65" (64 parameters for the cells content, and the 65th for the image width),
  • and a dummy named parameter (whose name is an empty string, and whose effective value results from the last assignment with the chessboard column names a to h and the surrounding spaces and newlines), which is not used in the internal template content.

Note also that all parameters are trimmed, so the parameter with autogenerated name "9" (at position a7 on the chessboard above) is assigned the empty string value.

Relative name for transcluded page

A page A can transclude a subpage A/B using {{/B}} or, with more control over the name of the page to be transcluded, this name can be constructed from {{PAGENAME}}.

This allows copies of the same wikitext in different pages to transclude different pages. Thus for example, the same wikitext, adapted from [2], containing a list of calls {{/lang|..}}, can be used in various ways on different pages, for example List of Wikipedias/lang/demo‎ and List of Wikipedias/local names‎, by varying the content of the subpage. A transcluded page need not use all the specified parameters. Two pages can share the same transcluded page using a redirect.

Template page

Without noinclude and includeonly parts the following are identical:

  • the rendering of the wikitext of the template (this is on the template page, and would be the same in other pages with that wikitext, except for page-dependent variables)
  • the rendering of the template on a page that calls it without parameters

Thus the defaults are shown, e.g. Template:Timc shows the same as {{t 1}}: "Template:T 1".

Template page if no defaults have been specified

In simple cases this corresponds to treating the parameter tags as ordinary text, for example:

"{{t2demo}}" (using Template:t2demo containing [[:Template:T2demo]]) gives Template:T2demo

Similarly, if part of the parameters is undefined, only those show up as {{{parameter number or name}}}.

However, often the rendered page produces a seemingly arbitrarily mutilated version of its content:

  • {c|Pink|NEW EXAMPLES GO HERE.}}


For parameters without default a workaround is less needed because the result in the case a parameter is undefined is of limited use anyway. If one wants it anyway one can put nowiki tags around the parameter; for the first example this gives "{{{1}}}p".

Less surprising, but nevertheless limiting the usefulness of the result are:

  • {{if}} applied to a parameter tag without default produces the then-part, the else-part is not shown.
  • {{ifeq}} typically produces the else-part only.
  • Variable tags are not shown, but evaluated.
  • A switch typically shows the default only.

In such cases includeonly can be used to avoid uninformative and messy rendering on the template page, but either way a disadvantage during template development is that preview does not (meaningfully) reflect changes in the parts of the page outside the noinclude tags (i.e. the included parts). Therefore it can be useful to provide representative default values, even if that is only done temporarily during development of the template.

With noinclude an informative template page can be produced, containing more demos and test cases than just the single default set. Typically, the noinclude-part of a template page contains examples including or substituting the template. Changes in the working of the template (i.e. changes outside the noinclude-part) are not yet effective in these examples in preview and, in the case of substitution, in "show changes". However, they are reflected in the rendered page after saving.

Some formatting aspects may show up which are not readily seen from the edit box.

A parameter value depending on parameters

As mentioned above, if a parameter is left undefined, the triple braced parameter name in the result does not function as a parameter if the page is called as a template from another page; if it should, do not omit the parameter value but specify it in terms of a parameter of the calling page; compare:

The most straightforward way of expressing a parameter value in terms of a parameter is using the same name and making it equal, e.g. {{Lan is|lr=af|le={{{le}}}}} in Template:Lan is mr.

Empty vs. undefined

{{t2demo||a}} makes the first parameter equal to the empty string rather than leaving it undefined: it gives Template:T2demo. By treating the second unnamed parameter as a parameter with the name "2", the first unnamed parameter can be left undefined.

Example: {{t2demo|2=a}} gives Template:T2demo.

If the parameter is used in a tag like <font size> the default text may give invalid code that is conveniently ignored, rather than resulting in perhaps ugly code being rendered (but this may depend on the browser). See e.g. Template talk:Fontsize.

Parameter names (as opposed to template names) are case-sensitive, even with respect to the first letter, and spaces are distinguished from underscores. The empty string is also a valid parameter name, see Template:T empty string as parameter name.

Parameter 02 is distinguished from parameter 2: using Template:Timc, {{t pl0|5|6|7}} gives Template:T pl0

Note that parameters in the system messages (MediaWiki namespace]] are written differently: as $1, $2, etc.

msgnw

The prefix msgnw (short for "message, nowiki") is used to display the uninterpreted wikitext of a template (the same thing you'd see if you were editing the page) on another page. An exception is that numbered and unnumbered lists are rendered as such instead of displaying # or * signs. Parameter values are ignored.

With the introduction of noinclude and includeonly tags, allowing template pages to take care of definition as well as displaying information, msgnw displays no longer just the technical information about what the template does when included, but a mix of that with wikitext for rendering the template page itself, with the tags. This limits the usefulness of applying this.

Examples:

Template:en

  • {{msgnw:en}} gives [[:Template:En]]
  • {{en}} gives Template:En

Template:Links-small

{{msgnw:t|a}} gives

  • <span title="{{{1}}}">{{{2}}}</span><noinclude>

==Usage== this template is for easily making titles on your text: just type <code><nowiki>{{t|what you want the title to be|text you want titled this}}</nowiki></code> so you could type <code><nowiki>{{t|Food|Pie}}</nowiki></code> and it would produce {{t|Food|Pie}} [[Category:Utility Templates|{{PAGENAME}}]]</noinclude>
...which is much more than just the formal info about what the template does when included:

  • start-{{{1|pqr}}}-end

Template:Numbered list demo

{{msgnw:Numbered list demo}} gives: [[:Template:Numbered list demo]]

{{Numbered list demo}} gives: Template:Numbered list demo

The edit box for Template:Numbered list demo shows:

#Amsterdam
#Rotterdam
#Little Rock

Usage

A template is useful for any text for which one wants a copy in two or more pages, and there is no need for each copy to be edited independently to adapt it to the page it is in. Since parameters can be used, versions may to that extent even be different, and parameter values can be edited independently for each. Templates are not only convenient, but they can also "force" a useful uniformity. See also advantages of subprograms.

A template can also provide structure (e.g. a table structure, colors, and other formatting) while the content varies (fully or partly) through parameters and variables.

A template can also carry out computations, comparisons, etc. using ParserFunctions, where the result(s) vary again through parameters and variables. See e.g. Category:Mathematical templates.

Typical applications are:

Various combinations are possible. E.g., the last two could be combined, so that e.g. every language version of Wikipedia has the same Infobox Countries template (for each project a copy, because the template mechanism can not import across projects), which has parameters for the data, and refers to templates with translations of standard terms.

See also Help:Advanced templates.

Composite pages

The wikitext of a page may (partly or fully) consist of tags for the inclusion of component pages. The "templates" are not necessarily in the template namespace, and may be more or less self-contained pages by themselves. A disadvantage of putting the components in the template namespace is that the component page may, by itself, be of a nature that it belongs in e.g. the main namespace, while the prefix would suggest otherwise; also the prefix would clutter the pagename.

Examples are:

This allows the user the choice between viewing the component pages separately or combinedly. One may want to view a page separately if one has a slow connection; also sometimes people have sentimental reasons for having a separate page about a topic, e.g. a village. Viewing the combined page is much more convenient if there are many small component pages; even if a subbtopic page does not provide additional info, if it exists anyway, and is linked to, it is useful to display the content (making clear that the whole content is shown), it saves the trouble of checking the contents by following the link.

In the latter case the search function of the browser can be used for searching in the combined page. Similar to the section editing feature, it allows editing a component page; however, there is no possibility to have the combined wikitext in the edit box.

Edit history, recent changes, watching pages, and "what links here" work separately for the component pages and the composition page, not for the composite page. Related changes works for the component pages and for the composite page. Page protection can be set for selected component pages and for the composition page, not directly for the composite page.

The talk page of a composition page is used to talk about the composition and the page in general, and could in addition be a composite page of the talk pages of the component pages.

A composite page has an integrated TOC and section numbering; the numbering is not reset for each component page.

Editing a section of a component page can be done directly from the composite page, see editing sections of included templates. After saving, one ends up at the page for the component page to which the section belongs.

On projects with the interlanguage link feature the composite page shows the combined interlanguage links of all component pages, hence possibly multiple links for one language or even for one page.

For easy access to the component pages, links to them on the composite page (for example by self-links on the component pages) are convenient. Alternatively, access is through section editing, or, if the component pages are in the template namespace, through the list of templates called from the composite page, at its edit page.

Conversely, for easy access from a component page to the composite page(s) that call(s) it (if there are not too many of them) it is convenient to link the component page to them (on a composite page one becomes a self-link).

See also w:Wikipedia talk:Template namespace#transcluding prose.

Pages with a common section

A section on the relationship of the subjects A and B, or a subtopic equally relevant for A as for B, can be put both in page A and in page B, by making it a separate page C, called as a template from A and B.

Remarks:

  • For readers reading both A and B, it is useful that the duplication be indicated by a message or a special lay-out; otherwise it is confusing and inconvenient. One can for example use Template:Links-small: Template:Cs
  • After saving one ends up viewing the template page. For easy access to the calling pages it is convenient to link the called page to them (on a calling page one becomes a self-link). This may well be integrated in the message about the duplication. It is even more convenient than the two-step link as shown above.
  • The section level of the embedded section(s) has to be the same in each embedding page. The same applies to lay-out and style.
  • Pages like C can be put in
    • the same namespace as A and B; advantage:
      • the kind of content of C is the same as that of A and B
    • the template namespace; advantages:
      • C appears in the list of templates called from A and B, at their edit pages
      • C by itself may not satisfy the standards for pages in the namespace of A and B, such as providing context (however, the message about the duplication explains it)

Examples:

For various remarks which also apply here, see also the previous section.

Repetition within a page

For a succession of similar pieces of content, as in a list, a computer program would use a loop. What comes closest in MediaWiki is putting the loop body in a template, and calling the template repeatedly, usually with a varying parameter value. This is somewhat primitive for a loop:

  • instead of "for i=1 to 5" we need to enumerate the values 1, 2, 3, 4, 5; on the other hand, this gives the versatility to use just as easily less regular values such as de, en, fr (collection-controlled loop).
  • repetition of code is minimized by the template, but the template call itself has to be repeated each time (but see also the next section)

Example:

  • Template:List of Languages - the "loop body" is in Template:Lang def; compared with putting the content of the latter directly in the list the advantage is that the variable part (the value of "code") occurs once each time in the code, although it is used twice. This is important because the fixed part of the list item code can be copied while the variable part is typically inserted manually.

The list of template calls can be in another template, with the name of the called template equal to or depending on a parameter, see e.g. Template:Tim.

For repetition of the same text the loop body can be a parameter, e.g. Template:X5 (see list).

A double loop is achieved by a second template that repeatedly calls the first. Similarly for a triple loop, etc. See e.g. w:Template:Ld, w:Template:L2d, and w:Template:L3d.

An example where the same template is used for different loop levels is Template:Loop 2. Because the software has a built-in protection against infinite nesting (if there is, there will be an error e.g. Fatal error: Maximum execution time of 30 seconds exceeded in /w/includes/Parser.php on line 775), a redirect is used for each level. The number of levels that the template can handle is determined by the number of parameters specified in the two template calls it comprises (because going up a level requires an extra parameter) and the number of existing redirects.

Similarly Template:Lanlp 1 is used for both the inner and the outer of a double loop. Adding an item (here a language) adds to each row and also adds an extra row.

Providing effective repetition without repetition of similar template calls in the wikitext

A technique for repetition of similar template calls without actually putting this list in the wikitext is demonstrated in Template:Links-small, and a more primitive method described below.

Example (using Template:t2demo containing "Template:T2demo") (see the master text at m:Help:Template#Repetition_within_a_page, on Wikipedia template "for" is different):

{{for|; |call=t2demo|pc1=constant|abc|def|ghi}} gives:

Template:For

Description of the old Template:Links-small:

For an arbitrary template with up to three nameless parameters, it is equivalent to calling the template repeatedly, with the first parameter varying, and the possible other parameters fixed: one specifies the name, the values of the fixed parameters, and the list of values the first parameter should have in consecutive template calls, with a sequential number each, and ending with "end". The technique requires redirects like Template:List of template calls 3, as many as the maximum number of repetitions.

If e.g. the second parameter varies, or two parameters, then a similar template can be made, but each version requires its own set of redirects.

Example (using Template:t2demo containing "Template:T2demo"):

{{List of template calls|t2demo|constant||abc|1|def|2|ghi|end|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||}}

gives:

Template:List of template calls

The empty parameters are needed in accordance with the maximum number of parameters the repeated template can have (currently three) and the maximum number of repetitions. Putting more empty parameters than needed at the end does not matter, but the number of empty parameters in the beginning of the list should be correct.

See also Help:Recursive conversion of wikitext.

Ambiguity of a reference to "this page"

If a page is included in another page, a reference to "this page" on the included page is ambiguous. Use noinclude or includeonly tags depending on what is meant. Alternatively, mention the page name explicitly, without using {{PAGENAME}}.

Internal links

In the case of an internal link in a template with the target depending on a parameter, and in the case of a link with the target depending on a template, existence detection works as usual.

Examples:

Templates and external links

Examples:

However, a URL can not be composed of:

  • a first part in a parameter and a second part added by the template (although we have seen above that reversed it works: a second part in a parameter and a first part prefixed by the template)
  • a first part in a template and a second part after the template (although we have seen above that reversed it works: the second part in a template and the first part before the template)

Example of first restriction:

Examples of second restriction:

Noinclude, includeonly, and onlyinclude

This feature is not available before version 1.6. These features are applied as nesting pairs, or 'Blocks', as it is said they enclose the material so that they can be said to begin and end a block of wikitext (code).

noinclude blocks

Anything between <noinclude> and </noinclude> will be processed and displayed only when the page is being viewed directly; it will not be included or substituted. Possible applications are:

  1. Categorising templates, see template documentation.
  2. Pages in the MediaWiki namespace.
includeonly blocks

The converse is <includeonly>. Text between <includeonly> and </includeonly> will be processed and displayed only when the page is being included. Applications include:

  1. Adding all pages containing a given template to a category, but not the template itself.
  2. Avoiding messy rendering on the template page, e.g. Template:Evaldemo.

Note that spaces and newlines between the general content and the tagged part belong to the general content. If they are not desired the include tag should directly follow the content on the same line:

<noinclude>this is </noinclude>fine<includeonly>, closing tags are
</includeonly><noinclude>
less critical, but must be specified.</noinclude>
nesting

Nesting an includeonly block within a noinclude block (or vice-versa) is legal but pointless.

onlyinclude blocks

With <onlyinclude>wikitext</onlyinclude> on a page, the display of the wikitext so surrounded and the rest of the page (except includeonly parts) is rendered on the page itself normally (note: this means interwiki translation links will behave as normal external links, unless they are further bracketed by <includeonly>). The demo page below holds a full screenful of text and code, including several includeonly blocks as well as a single onlyinclude block as a demonstration. It is advisable to look at that page in edit mode.

However, in transclusion, the page gives only the parts within onlyinclude blocks. Using the test line:

Using [[Help:Template/onlyinclude demo]], 
     <nowiki>{{Help:Template/onlyinclude demo}}</nowiki> 
          gives '''{{Help:Template/onlyinclude demo}}'''. 

When repeated below we get: Using Help:Template/onlyinclude demo, {{Help:Template/onlyinclude demo}} gives Help:Template/onlyinclude demo. When that page is included, it does not even transclude other blocks which are defined as includeonly parts, unless such are also within the onlyinclude block. So on a page with onlyinclude tags, text within includeonly tags is never rendered, i.e., it is reduced to wikitext comment. See also Help:Template/onlyinclude demo 2 and its talk page.

Caveats on splitting and interworkings

Attempts to nest split pairs of these tags, or the similar <nowiki> and </nowiki> pair, won't work as expected.

If say <nowiki> begins within the general page content, or in a "noinclude" part, or in an "includeonly" part, then it also has to be closed within the same part.

The code ~<includeonly>~</includeonly>~~ will be displayed as ~~~ when the template is not included, ~~~~ when the template is included, but it will only be expanded as the active user when the template is subst'd, which is to say when it has been joined within the same block once again.

Wiki markup at the beginning of a template

If the first included character of a template is one of the Wiki markup characters :;*#, then it's interpreted as being at the beginning of the line (even when the template call is not).

To avoid this effect use <nowiki>#</nowiki> or a numeric character reference (NCR) or HTML entity like say &#58; for a colon. This NCR is also useful in conjunction with definition lists.

Substitution

Main article: Help:Substitution

Putting "subst:" after the double opening braces causes an automatic conversion of wikitext when the referring page is saved: the subst tag is replaced by the wikitext of the template, with the parameter values substituted for the parameters.

For optional multi-level substitution of templates add {{subst|}} after the opening braces in all calls of templates, parser functions and variables in templates, and add "subst=subst:" to the parameter definitions of all templates. Use additional similar parameters for selective substitution.

Also use the alternative way of specifying a parameter default: always except for {{{subst|}}}, or just in cases where it is needed as workaround for the bug regarding an undefined parameter with a default in a parameter of a parser functions//wiki.urbandead.com/index.php/Help:Substitution#Corrupted_default_value, i.e., in parser functions, if the parameter name is one of the affected ones.

Redirection

When a page called for inclusion is a redirect page, the redirect target is included instead. As usual, a double redirect does not work.

A page that consists of nothing else than the inclusion of another page as a template, shows similarities to a redirect to that other page, but also many differences, including:

  • the result has as header the name of the referring page
  • there is no redirect message
  • the buttons such as edit (for editing the whole page), watch, talk, history, "what links here", and "last modified", etc., refer to the referring page (to go to the target page, a section edit link can be used, from there the whole page can be accessed)
  • the referring page is in the same categories as the target page, except when includeonly and/or noinclude tags are used
  • "double redirects", with one or both being this kind of "pseudo-redirect", work.
  • for the Template:Peisl it is disadvantageous to include the target page: the pre-expand include size is the sum of the pre-expand include size of the target page and the size of its wikitext; since typically the wikitext of a page is much smaller than this maximum, this is only an extra complication if the pre-expand include size of the target page is already close to the maximum.


Compare Help:Template namespace with Help:Template namespace - demo of alternative for redirect.

In a page that in turn includes such a referring page there is no difference.


Note that embedding works for all pages where redirecting works, and it also fails for all pages where a redirect won't work.

Self-transclusion

A page can transclude itself, but is protected against an infinite loop: the transclusion in the transcluded copy of the template is replaced by the bolded pagename. See Template:Pim and Template:Pim.

Transcluding on page A page B redirecting to page A allows more repetition, see Template:Pim with Template:Pim.

If due to the use of braces hidden in a template (see Help:Recursive conversion of wikitext) the saved wikitext of a page contains a substitution call to itself, then on the next save the substitution is applied for one level; the transclusion in the transcluded copy of the template is replaced by a link to the pagename. Thus it becomes a self link, i.e., it becomes bolded text with immediately following characters also bolded. This time the link is followed in the wikitext by the hidden message "<!-- WARNING: template loop detected -->"; see [4]; this edit was automatic by edit/save without making a change in the wikitext oneself.

Parsing braces

If some braces are "hidden" in a template, as in Template:Links-small, then parsing of pairs of double and triple braces is based on visible braces only. In the case of partial substitution, first parsing is done for the purpose of substitution, then parsing is done again for rendering:

  • {{t1|{{lb}}tc}}}} gives Template:T1}} - the last-but-one pair of closing braces is taken as closing braces of Template:Links-small
  • {{t1|{{subst:lb}}tc}}}} gives the wikitext {{t1|{{tc}}}} rendered as Template:T1 - after substitution the last pair of closing braces is taken as closing braces of t1
  • {{subst:t1|{{subst:lb}}tc}}}} gives the wikitext start{{tcend}} rendered as startTemplate:Tcend - the last-but-one pair of closing braces is taken as closing braces of t1 for both substitutions
  • {{subst:subst}}t1|a}}, substituting Template:Links-small, gives the wikitext {{subst:t1|a}} rendered the same; in the next edit the wikitext is converted to "startaend".
  • {{subst:tsubst 1|a}}, substituting Template:Links-small: ditto.

See also Help:Recursive conversion of wikitext.

Comparison of linking and embedding

Linking and embedding have in common:

  • if the page does not exist, a link to the edit page is shown; the links are identical if it is not a piped link; the link does not show parameters and does not show whether, after creation, the new page will be linked or embedded.
  • the name can depend on variables and parameters


Template expansion

Expanding a template call internally involves, to start with, identifying the parameter name part and each parameter definition part, based on separators "|", excluding those inside pairs of double and triple braces and double square brackets (as far as explicit in the wikitext of the outer template call, hence not counting "|" in e.g. the content of an inner template). Each part is expanded, after which each parameter definition part is separated, if applicable, based on the leftmost "=", into a parameter name and a parameter value. Executing these parameter definitions from left to right, an associative array of (name, value) pairs is constructed with unique names, including numbers for unnamed parameters.

Expanding a predefined template and expanding a template parameter tag involves the same, as far as applicable.

It follows from the above that a "|" in the expression for the value of a parameter or parameter default can only be inside pairs of double and triple braces and double square brackets. To obtain a parameter definition which expands to wikitext containing "|", this character has to be in the content of an inner template, parser function, or parameter value, see e.g. Template:Links-small..

Expansion of wikitext is relevant even if the wikitext resulting from these subevaluations cannot have effect on the overall wikitext, as in the case of #ifexpr etc. for either the then-part or the else-part, and in the case of an unused template parameter:

  • Subevaluations involving template calls add to the pre-expand include size (see Wikipedia:Template limits).
  • Side effects:
    • Subevaluations producing links add on the target page to the list of incoming links (What links here), based on the pagelinks table, even if there is no link on the resulting page.
    • Subevaluations involving template calls add on the template page in "What links here" and on the edit page of the page concerned to inclusion items, based on the templatelinks table.
    • Some extensions may perform some action during a subevaluation, e.g. with VariablesExtension a subevaluation may involve assignment of a value to a variable.

Thus {{ #ifexpr:.. | {{a|parameters}} | {{b |parameters}} }} evaluates {{a|parameters}} and {{b|parameters}} regardless of the condition. On the other hand, {{ {{#ifexpr:..|a|b}} | parameters }} just evaluates the expression for the template name (by evaluating the condition, and resulting in a or b) and the parameters, and the actually included template.

See also ParserFunctions#Code_execution.


Revision history of pages containing templates

Pages in the stored page history consist of wikitext with possible references to templates and images. When viewing an old version of a page, these refer to the current versions of the templates and images, if these still exist. Thus the former composite page is not reconstructed.


See also

Template:H:f