Help:Template

From Wikiquote

Template:H:h

In MediaWiki, a template is a page which can be inserted into another page via a process called transclusion. It is comparable to a subroutine.

This page and its extension Help:Template names, variable names and parameters depending on a variable or parameter provide a reference manual on templates in MediaWiki. For an introduction, see A quick guide to templates.

Notes:

  • The master version of this page is the page m:Help:Template on Meta-Wikipedia; template demos work there, but may not work if you are viewing a copy of this page on another project.
  • Templates can be used to control (part of) the page body, but not the margins (logo, sidebars, etc.). These are controlled by the skin, the user style, and part of the contents of the MediaWiki namespace.

General

The template namespace is the namespace with prefix "Template:" (this prefix can be used in all languages, but the canonical prefixes in languages other than English include Vorlage, Modèle, Sjabloon, with colon; the site WikiFAQ calls it Snippet).

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 (, creating a compound document).

The syntax for insertion of the page "Template:name" is {{name}}. This is called a template tag. Example: abc{{tc}}def Template:Ut1 gives abcTemplate:Tcdef.

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

  • calling the template
  • referring to the template
  • including the template
  • transcluding the template
  • using the template

If the page "Template:name" does not exist, then {{name}} works as [[Template:name]], a link to a non-existing page, leading to the edit page. Thus, one way of making a template is putting the tag first, and then following the link.

If name starts with a valid namespace prefix, or a colon, then it is not prefixed with "Template:". This way any page can be used as template (a colon at the start refers to the main namespace).

However, a page in the template namespace has advantages:

  • they are listed on the edit page of pages that call the template
  • when a page in the template namespace is changed, all the other pages that link to it automatically have their server caches (as opposed to browser cache) purged. With other namespaces, you need to purge the server cache manually.

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.

In the case of an image or category, it gives the description part. E.g. {{Image:tst.png}} gives File:Tst.png. However, if the image is on commons, the template call is treated as a link, which in turn is the embedding command, so the image is embedded: {{Image:Map South Holland.png}} gives:

File:Map South Holland.png

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

  • quoting interface messages in the MediaWiki namespace
  • experimenting with templates in subpages of one's userpage
  • using as the caption of an image the editable part of its image page
  • 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}}.

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

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

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 templates used on a page, all with links, is given on the edit page. Notes:

  • only those in the template namespace are given, not pages in other namespaces, transcluded in the page
  • even on a section edit page the whole list is given, i.e. also the templates used in other sections
  • even when editing an old version of a page, the list is given for the current version
  • templates for which the tags have not been saved yet are not shown, even on the preview page

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

using Template:Numbered list demo, gives

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

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. 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. m: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
Those on the central Wikicities work in the separate Wikicities projects, provided that the prefix "wikicities:" is used, see wikicities:Help:Shared templates.
Please note that these external Wikicities projects are NOT hosted and managed by the Wikipedia Foundation.

Parameters

Template parameters are either named or numbered. They are called-by-value, and therefore input parameters only. Template:MW 1.6 The syntax is {{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. Thus the formal parameter (the placeholder for the parameter value) is the parameter name with three pairs of braces.

Thus the template mechanism involves the following steps:

  • in template calls the template name, parameter names and parameter values depending on variables are evaluated; the result of this step can be viewed by applying subst (possibly multiple times), save and edit, see below; in the case of a variable depending on a variable this may have to be done a second time;
  • 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 instanciation 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.

Spaces before or after a parameter value are normally ignored:

"{{t|a}}" Template:Ut1 gives "Template:T".
"{{t| a}}" gives "Template:T".
"{{t|a }}" gives "Template:T".

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

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

(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 Template:T.

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

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

Template calls can contain multiple occurences 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 occurence (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 formal parameters before the template itself is instanciated is then unordered because the list is indexed by the evaluated parameter named (this list is an associative array).

A useful example that uses of multiple assignments of parameters with the same name (and thus allowing parameter overrides) is performed in the en:Template:If defined call1 template used for example in English Wikipedia (and many other localized editions).

Restrictions on parameter values

  • If a parameter value contains an equals sign, the parameter name must be put explicitly, even when it is 1, 2, 3, etc.
  • If the expression for a parameter value contains two consecutive closing braces which are not part of a variable or parameter tag, they have to be put in nowiki tags.
  • If the expression for a parameter value contains a pipe character (|) which is not part of a piped link or within an image tag, it has to be put in nowiki tags: <nowiki>|</nowiki>.
  • The expression for a parameter value cannot contain the variable localurl with query string, due to the pipe character.
  • A parameter value can contain pairs of square brackets or text to be used within a link, but not a closing part of one link and an opening part of another link: {{tlis|abc]]def[[ghi}} using Template:Timc gives {{tlis|abc]]def[[ghi}}

Named vs. numbered parameters

Advantage of numbering:

  • in the template call no name or "=" is needed; this means less to type and also less to memorize or lookup (on the other hand, one has to memorize or lookup the order); an exception is when the value contains "=": then the other equals sign is needed, with the parameter number in front.
  • numbers are international, both in the template tags and in the parameter tags in the template, no parameter name has to be translated (alternatively, one can e.g. use English names, only editors would see them and need to understand them)

Advantages of naming:

  • the order of specifying the values does not matter
    • a dummy unnamed parameter for comment and for formatting the template call can be inserted at any time, without planning in advance or renumbering (in the case of unplanned insertion of a dummy parameter between numbered ones, the text has to contain an equals sign; this works even if there is a newline somewhere before the "=", although a newline is not allowed in a parameter name).
  • the template is easier to understand
  • some special techniques use the fact that multiple assignments of values to the same parameter in the same template call is allowed and results in the last value being used; this implies that at least one parameter name is specified explicitly in the template call

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.

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:Ut,

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

{{chess position|=

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

|30}}

which gives

Template:Chess position

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 "17" (at position a6 on the chessboard above) is assigned the empty string value.

Effect of an undefined parameter if no default has been specified

Some parsing problems in earlier versions of the software have been fixed; using Template:Tcw:

Template page

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)
  • 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:

"{{t2}}" (using Template:t2 containing [[:Template:T2]]) gives Template:T2

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

However, if a parameter is in another template call, then, as a result of what was explained in the previous section, the template page seemingly demonstrates an error in the wikitext: it is confusing, as a result of parsing the code differently from when it is used, i.e. called with a parameter value.

E.g., the template page of Template:Tcw shows Template:T2a1, and that of Template:Tcw shows Template:T2a3.

Thus, for getting informed about the contents of a template, just looking at the template page is insufficient (because it is ambiguous) and misleading. Note also that variable tags are not shown, but evaluated. However, some formatting aspects may show up which are not readily seen from the edit box.

Template talk page

The template page is of a different nature than other pages. It is not for explaining anything to the reader, but for defining the template for the system (this is done by the wikitext, the rendered page is just a by-product). Therefore the template talk page has an especially important role. It typically consists of two parts:

  • the first part explaining the template and its parameters
    • preferably examples are given of template calls (put them in nowiki tags) and the results (put the template call without nowiki tags in the wikitext)
  • the second part used for the ordinary talk page function

In complicated cases, "subst:" can be very helpful in the explanation, see below.

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.

Remarks

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

Example: {{t2|2=a}} gives Template:T2.

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 MediaWiki namespace (interface messages) are written differently: as $1, $2, etc., see Meta-Wikimedia:MediaWiki namespace text.

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 accidently, 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}} Template:Ut1 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 perameter "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"). In this case, if template TTT had a perameter {{{3}}}, {{TTT|1=a=b|2=c|d}}, "d" would be assigned to "3" as first implicit parameter without a value.

The same applies if a parameter value depends on a parameter, and may therefore contain an equals sign. Compare:

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.

Examples:

Template:en

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

Template:t2

  • {{msgnw:t2|a|b}} gives [[:Template:T2]]
  • {{t2|a|b}} gives Template:T2

Template:Numbered list demo

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

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

The edit box shows:

#Amsterdam
#Rotterdam
#The Hague

Link for editing a template

An edit page shows template tags in the edit box, not the wikitext of the included templates. A list of links is provided to the templates used on the page. To edit a template, one can follow the link, and go to the edit page of the template.

More convenient is to have a special link for editing the template on the calling page. This link can be put in the template itself. Since these edit links are similar for various templates, it can be made a template itself, with the name of the template as parameter. See e.g. and.

On Meta there are:

For editing a template ({{{1}}} is the name without prefix):

For editing any file ({{{1}}} is the full page name):

For a template containing only one paragraph or less, without links or images, one can also make the whole contents link to the edit page, see Template:Timc.

This is e.g. convenient for editing an individual entry in a table, without having to search in the wikitext of the table.

Help:Editing sections of included templates

Usage

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

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:Template names, variable names and parameters depending on a variable or parameter.

Navigational templates

A common, simple type of navigational template in a hierarchy of pages is one with the names, with links, of a parent page and child pages. It is placed on all the pages it lists. Thus a page that is not at the top or bottom of the hierarchy has two templates, one with its parent and siblings, and one with its children.

Variations also occur, such as pages having two parents, etc.

Self links do not give any complication: they are neatly displayed in bold and not as link. However, templates should have the correct page names and not rely on redirecting, since the feature does not work in that case. Also for a link to a section the self-link feature does not work.

A navigational template may also just allow going forward and backward in a linear sequence, e.g.. For the predecessor of the first and the successor of the last a message like "none" can be used. This is not applicable in the case of a cycle, such as the days of the week.

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. An advantage of putting the components in the template namespace is that they are then included in the list of templates used on the composite page, all with links, on its edit page. On the other hand, 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:en: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 is indicated by a message or a special lay-out; otherwise it is confusing and inconvenient. One can for example use Template:Tim: 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.

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:en:Template:Ld, w:en:Template:L2d, and w:en: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 m:Template:List of template calls. 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 Template:Ut1:

{{List of template calls|t2|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.

Images in templates

New: In a template, image code parameters can contain template parameters, e.g.

{{timgi|wiki|50|small}} {{timgi|wiki|100|medium}} {{timgi|wiki|200|large}}
{{timg1|st|50|pqr}} {{timg1|st|100|st}}

using Template:Tcw and Template:Tcw

give

Template:Timgi Template:Timgi Template:Timgi Template:Timg1 Template:Timg1 Template:Clr For cases for which an image is not applicable or available, use a dummy image such as w:en:Image:No image.png.

For an image in a template that should be different for each page in which the template occurs, there are also the following possibilities:

  • a parameter value can contain the whole image code: {{t|[[Image:Tst.png|50px|bullet]]}} gives Template:T
  • in projects where external images can be embedded, the url of the image can be a parameter: {{t|http://meta.wikimedia.org/upload/2/27/Tst.png}} gives Template:T
Note that this does not work on projects hosted by Wikipedia, due to local restrictions about external references to embedded images (or objects or scripts or stylesheets): these images can only come from the local projet (and will be served by the "http://upload.wikipedia.org/" base URL, the complete effective URL being computed and forced by the special [[Image:]] template), or alternatively the images can be imported automatically from the Wikipedia Commons project where they will be found if they are not present in the local project.
Without this restriction, meant for security, it would be possible for any visitor to include the external reference of an image hosted somewhere else, that would either violate a copyright notice, or would contain in fact another object than an image, such as a malicious script that would be downloaded automatically by the browsers used by all visitors of the Wikipedia article that embeds such fake image.
  • the image is given a name of the form prefix{{PAGENAME}}suffix (with a suffix, consisting of the file name extension and possibly more, and possibly also a prefix). See examples below. Note that there is little flexibility: changing the name of a page in which the template occurs requires uploading the image again, with the corresponding name.

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:

Interwiki links

Templates can contain interwiki links; this normally means all pages using the template will have the interwiki, which is usually a bad thing unless some fancy footwork is done. To link just the templates across wikis, use the <noinclude> tag. For example:

<noinclude>
[[de:Vorlage:Korrekter Titel]]
[[en:Template:Wrongtitle]]
[[es:Plantilla:Título erróneo]]
[[fr:Modèle:titre incorrect]]
</noinclude>

Be careful when adding categories or interwikis within templates which are meant to be used inline, including within tables or lists: don't add newlines before <noinclude> or after </noinclude> because they will be kept in the resulting wiki code used to generate the page that references that template.

It is recommanded to insert <noinclude>...</noinclude> at end of articles and templates, by first dropping the newline present at end of all existing articles and templates. The single newline that Wikipedia requires or adds automatically after </noinclude> is discarded when the template is instanciated for rendering the articles that include it.

See also below.

External links

With external link style much is possible. A blank space in a parameter value or template content that is substituted in a URL is not taken as ending the URL, but converted to %20.

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:

  • [{{th}}add at the end] Template:Ut1} gives [[[:Template:Th]]add at the end]
  • "{{th}}add at the end" gives "Template:Thadd at the end"

Navigational images

The following applies in projects where external images can be embedded.

Examples where the label contains an image and depends on the parameter or template:

With external link style:

Notes:

  • the c and d are used to show the more general case, without them the label is instead of contains an image, with perhaps [[help:link|{{timgurl}}]] giving [[help:link|Template:Timgurl]] the more useful kind.
  • the target can be made variable like above.


EasyTimeline code with a template parameter is not allowed

Template talk:Etl


Noinclude and includeonly

This feature is not available before version 1.6.

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

  • categorising templates; including a page in another page without putting the including page in the categories the included page is in; in particular this is useful when including an article in a user page or test page
  • interlanguage links to similar templates in other languages (Otherwise such a link appears in the edge of the page that includes the template, giving the impression that the link is to a version in the other language of the referring page instead of the template. The link label depends only on the sister project that is linked to, not on the page; it is set in the configuration of the project, typically it is the name of the language in that language. The target is only shown in the hover box and the status bar, depending on the browser.) - see also above.
  • pages in the MediaWiki namespace
  • explanatory text about how to use the template

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

  • Adding all pages containing a given template to a category

Note that the usual update problems apply -- if you change the categories inside a template, the categories of the referring pages won't be updated until those pages are edited.

With these tags a page can also call one of two specified templates with the same parameters, depending on whether the page is included in another page, by putting the tags in the template name part of the template call, as in Template:Timc. See also Template:Pi, where page content is arranged such that a selection of it can be displayed in a different format in a table row.

"subst" (see below) includes everything, also these tags.

Note that spaces and newlines between the general content and e.g. the noinclude part are part of the content, so if they are not desired the include tag should directly follow the content without space and not on a new line.

A category tag in a template; caching problem

If a template contains the code indicating that it is in a category, this does not only put that template in the category, but also the pages that include the template. Thus this is typically not applied to categorize templates, but to conveniently put pages in a category, based on the template they use. For example, this page includes Template:H:h and as a result is in Category:English documentation.

The page that contains the template correctly lists the categories to which it belongs. However, adding or deleting a category tag in the template does not add or delete the listings on the category page of pages that use the template, until some edit is made in the page that uses the template.

In other words:

  • lists of categories a page is in, are up-to-date
  • lists of pages in a category are based on the situation just after the last edit of the pages

Since adding or removing a category or template tag is obviously an edit there is only a complication when a page is indirectly added to or deleted from a category, through a change in a template the page uses.

To refresh category pages with respect to the listing of a particular page (adding or deleting the entry), a null edit can be applied to that page: just applying section edit and saving without changes.

Thus, a basic principle of templates, that changing the contents of a template automatically changes the pages that contain the template, does not extend to these pages being correctly listed on category pages. It still works, with a delay, for sets of pages which are all frequently edited anyway, for other purposes.

In other cases the principle is violated. What remains is that just making null edits is somewhat less cumbersome than changing category tags in each page.

In conclusion, adding or deleting a category tag in a template that is already in use should be avoided unless one is willing to make the null edits, or is willing to accept the (possibly very long) delay during which there is no consistency between the category pages and the category listing on the pages in the categories.

Newline in a template

A single newline works like a space, except in a list, there it breaks the list. Since templates containing a single paragraph or less could be called from a list, such templates should avoid single newlines.

Indentation or list code at the beginning of template content

Each of the markup characters ':;*#', at the beginning of template content, is interpreted as being at the beginning of a line (even when the template call is not). This also applies to parameter values that appear at the begining of the template content. The effect can be disabled with nowiki tags.

Examples (nowiki examples use capital 'Def'):

abc{{p1|def}}ghi

abc{{p1|<nowiki>:</nowiki>D1ef}}ghi

abc{{p1|:d1ef}}ghi

abc{{p1|<nowiki>;</nowiki>D2ef}}ghi

abc{{p1|;d2ef}}ghi

abc{{p1|<nowiki>*</nowiki>D3ef}}ghi

abc{{p1|*d3ef}}ghi

abc{{p1|<nowiki>#</nowiki>D4ef}}ghi

abc{{p1|#d4ef}}ghi

gives:


Server cache impacts

When a template (in the Template namespace) is edited, the cache is cleared of all pages that include the template (at any nested level). When a page is viewed, and not in cache, the output HTML has to be reconstructed. Consequently, editing a template has a server impact (roughly) proportional to the number of pages dependent upon it.

For load constrained projects, template designers should consider long term edit impacts for templates that will be used in a large number of pages, particularly from template nesting. Projects may establish performance related policies, e.g. w:en:Wikipedia:Avoid using meta-templates, a guideline to avoid high-usage, nested templates.

The following can be used as a simple model. If a template is called from p pages and edited with a frequency e, while the pages are viewed with a frequency v, then the relative amount of work for rebuilding the page (as opposed to taking it from the cache) is, per unit time:

  • if e<v: pe (each time the template is edited, all pages have to be rebuilt)
  • if e>v: pv (each time a page is viewed, it has to be rebuilt)

If the edit frequency varies, then the amount of work for each time segment has to be considered separately, and added. For example, if a template is called from 1000 pages, each viewed once a day, and if each month four edits in a row are made to the template, then the first induces a lot of work (1000 page refreshings) and the other three very little. Compare this with having four edits spread over the month, i.e. every week a single edit is made to the template, which causes 1000 page refreshings every week, or 4000 for the month.

Note: some impacts (not distinguished here) occur immediately when the template is saved, others are distributed over the time when the template is used. Many additional factors need to be considered for an accurate cache model, too numerous and intertwined to be included here. The simple fanout and frequency model still applies as a first order estimate.

Stale cache purge

When a page in the Template namespace is edited, this automatically clears the cache of any pages which use that template. However, there are cases of indirect dependence where a page may still not be up-to-date, even after pressing Ctrl-F5 or similar. This is e.g. the case for pages (typically template talk pages) referring to, containing {{msgnw:{{PAGENAME}}}}, probably because the template page name referred to depends on a variable.

Pressing Ctrl-F5 or similar generally only refreshes the browser cache, not the server cache. To purge the page server cache and a force full update, use "action=purge", in a URL like //simple.wikiquote.org/w/index.php?title=Help:Template&action=purge .

Subst

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. However, "noinclude" and "includeonly" are not applied: everything, including these tags, is included. Subst can also be applied to a variable.

Example: {{subst:t2|[[a]]|[[image:tst.png]]}} Template:Ut1 will give the wikitext start-[[a]]-middle-[[image:tst.png]]-end, which is rendered just like {{t2|[[a]]|[[image:tst.png]]}}: Template:T2.

The replacement of a template tag by wikitext does not automatically work recursively: if the template calls another template, that tag is not replaced. One can subsequently add "subst:" again, thus doing manual recursion. This stepwise replacement can be useful for analyzing and explaining the working of templates calling other templates. See e.g. Template talk:Lop. However, it requires applying "noinclude" and "includeonly" manually, or, if the "includeonly" content is plain text (not used in a template name or parameter, etc.), at least disabling the "includeonly" tag by changing one character of it, in order to see the text.

It can also be used to create a page independent of templates, as a way to archive the rendered page and allow a permalink to it. See also bugzilla:2777, a request for a version of subst that automatically works recursively.

If you want to use a modified version of the resulting wikitext, you have to save the page with the unmodified wikitext first, then edit it, because when applying preview the subst code is not yet replaced in the edit box. In the edit summary of the temporary edit you can put "tmp" to indicate that you have not made an error but are still working on the page.

In the absence of parameters, an alternative that clutters the edit history less is, of course, copying the text from the edit box of the template page: then it can be edited before saving. Another method is using msgnw without saving, and copying the preview result into the edit box.

When subst is applied to a template:

  • a variable in the template is copied as such in the wikitext.
  • if the template call contains a variable, subst has to be applied to that variable as well, otherwise the first two closing braces of the parameter are interpreted as closing braces of the template.

Applying subst to a variable works like applying it to a template. E.g. a timestamp:

{{subst:CURRENTDAY}} {{subst:CURRENTMONTHNAME}} {{subst:CURRENTYEAR}},    {{subst:CURRENTTIME}} (UTC)

giving:

10 March 2005,    08:23 (UTC)

One might be tempted to put this in a template, but then it would display the time of creation of the template; on the other hand, without the "subst:", it would give the time of loading the page with the timestamp. Neither is suitable for a timestamp, which should give the time of saving the new referral to the template (like ~~~~~ does).

Usage of a template through "subst:" does not show up in page histories, backlinks, etc.

Input box

Similar to applying "subst:" to include page A in page B, in the case that B does not exist yet and that A does not have parameters, is using an inputbox to create B, preloading A. A difference is that the wikitext can be edited before saving.

Rewriting a template that calls other templates in a self-contained form

If a template calls other templates one may want to rewrite it in a self-contained form (i.e., which does not need other templates) in order to use a copy of it in another project, without copying more templates.

For example, Template:Tcw, calling Template:Tcw, could be written "start-a-middle-{{{1}}}-end".

To do this semi-automatically, one cannot use subst without specifying a parameter, or with {{{1}}} as parameter: the result of that is like the template page "t2a1" shows: "Template:T2a1". In fact this is how the confusing rendering of a template page can be analysed.

Instead, one can apply subst with parameter "{{{1}.}.}." and obtain "{{t2|a|{{{1}.}.}.}}". If we now remove the three dots again, we have the content of "t2a1" in a self-contained form: "start-a-middle-{{{1}}}-end".

Case where a template name depends on a variable or parameter

If template A calls a template whose name depends on a variable or parameter, subst can only be applied for specific values of that variable or parameter, each resulting in a separate new version of template A, not for the general case. Saving e.g. "{{subst:H:f {{NAMESPACE}}|langs=|enname=Template}}" does not change the wikitext (but the rendered text still replaces the effective variable or parameter value), which is rendered as just "{{subst:H:f Help|langs=|enname=Template}}", because the assumed template name contains braces, therefore the system concludes that the template does not exist.

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
  • "double redirects", with one or both being this kind of "pseudo-redirect", work.

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.

Math tags

MediaWiki templates, variables and parameters cannot be used within math tags, see Template talk:Demo of attempt to use parameters within TeX.

A template looked upon as a subroutine

The wikitext of a page can be looked upon as a list of statements, in which case a template is a statement-type subroutine. Alternatively the wikitext is a string expression, in which case a template is a string function.

In the first view, a{{b}}c is a sequence of three statements, in the second a concatenation of three strings.

In both views, the b in {{a|b}} is a string expression: the value of an input parameter of type string; however, the expression involves only concatenation, not (as one might think in the second view) any string function.

A subroutine is selected based on evaluating the string expression for its name (so this is done at "run-time"), so the process seems like that of an interpreter.

The subroutine is the only programming construct / flow control construct.

There are no variables/constants or assignment statements, except in the framework of subroutine parameters. The only operator (see operator and operator (programming)) is concatenation.

A template itself can also be considered an operator, with the number of parameters being the arity.

Simple computations

Simple additions and multiplications can be performed based on concatenation, using the unary numeral system: when 2 is represented by 11 and 3 by 111, then concatenation gives 11111, which can be converted to 5, see Template:Tim and Template:Tim. An additional parameter allows not only to display the result 5, but also to call a template of choice with parameter 5.

Required auxiliary templates:

  • for every value m used as first operand a template calcm containing {{calc{{{2}}}{{{1}}}|m digits "1" |{{{3}}}}}, see e.g. Template:Tim
  • for every value n used as second operand for addition a template calcAn containing {{countn digits "1"{{{1}}}|{{{2}}}}}, see e.g. Template:Tim
  • for every value n used as second operand for multiplication a template calcBn containing {{countn times {{{1}}}|{{{2}}}}}, see e.g. Template:Tim
  • for every result r a template countr digits "1" containing {{{{{1}}}|r }}, see e.g. Template:Tim
  • the template that one wants to call with the result as parameter; if one just wants to display the result, or use it in a link target, or in an image tag, one uses Template:Tim

In view of the maximum length of 255 for page names, the maximum result can be 250.

Note that for any computation one can prepare an array with all results, but the amount of work to do that is proportional to the number of pairs (m,n) that one wants to use, while above the amount of work is only proportional to the sum of the number of values of m, n, and r.

Linking to a template

Unfortunately, when linking to a template instead of embedding it, transfer of parameters is not possible. This would be useful e.g. for the following:

  • for a given image, allow links to pages each showing the image in a particular size, without having prepared a separate page for each size
  • for given geo-coordinates, link to a page such as w:Template:Mapeu with links to maps of that location; this would be like the Special:Mapsources feature, e.g. http://kvaleberg.com/wiki/index.php/Special:Mapsources/59_55_N_10_44_E, proposed as an extension of MediaWiki, except that no computations are possible, but, on the other hand, it would enable multiple editable "Map sources pages" in the form of templates.
  • Template:Table of Wikimedia projects provides a table of links to similar pages on all Wikimedia projects, depending on a parameter, e.g. all main pages, or all lists of templates. A page would be convenient with links to various of such tables, made on the fly.

Coming close to this is a page with links like Template pages and Template talk pages. These section edit links would each give access to one table through the preview. The whole page could be very large in rendered form, because the whole page would never have to be rendered (although on saving the system would attempt to do so even if it not desired). As far as the variation of the parameter for the last part of the URLs is easy, such as just changing the namespace number, not all tables need to be present, one can change the parameter in the edit box and get the desired table on the fly by the preview.

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

Extra possibilities of linking:

  • the name can depend on the content of templates; this is not possible for the name of an embedded page, not even indirectly: the name can depend on a parameter, but a parameter value or name can also not depend on the content of a template
  • the page referred to can be outside the project (interwiki and external linking)

Extra possibility of embedding:

  • there can be parameters, i.e. a single page can have different rendered content; this is not possible with a link; note that embedding a page with a link still does not allow the linked page to depend on parameters (see also the previous section)

Other differences:

  • the syntax {{..}} or {{..|..|..}}, etc., versus [[..]] or [[..|..]], with the pipe character having a different meaning
  • obviously the difference between having the pages rendered combinedly or separately
  • for embedding the default namespace is the template namespace (for the main namespace prefix a colon), for linking the default is the main namespace; prefixing a colon is also allowed, so one can use {{NAMESPACE}}:...

Developing templates and template tags

When adding a parameter to a template that is in use, one can first adjust the tags, and then the template. During the work in progress, the template keeps working properly, but the new parameter becomes effective only at the end.

Alternatively, a new template name is used for the new version, and while adjusting template tags, the template name is also changed (for convenience, this is typically a small change, e.g. one letter or digit is added or changed). The advantage is that during the work in progress, the new parameter becomes effective on a page as soon as the tag has been adjusted. Also, the backlinks of both templates show the pages that are done and that still have to be done.

To accommodate future expansion of a template, involving more parameters, one can in advance add parameters with the empty string as their value to the template tags. If unnamed parameters are used, one does not have to plan in advance the meaning of the new parameters.


Templates in different versions of MediaWiki

Version 1.4

  • Including the same template more than five times in the same page works from version 1.4, now on all Wikimedia sites. Also new was that subst can be used with parameters.

Version 1.3

  • See, among other things, [1].

Version 1.2.6

  • In MediaWiki version 1.2.6, make a page MediaWiki:mytemplate and refer to it with {{msg:mytemplate}}. In this version parameters are not possible.
  • Compatibility with 1.3, in the sense of having the content in Template:mytemplate, is possible with a redirect from MediaWiki:mytemplate to Template:mytemplate on the 1.2.6 project.

In versions 1.3 and 1.4 the prefix "msg:" is optional and ignored.

From version 1.5 the tag {{msg:abc}} refers to Template:Msg:abc !

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.


Reserved template names

According to the MediaWiki help policy some template names are reserved for use in the Help namespace. This allows copying without modification of the wikitext of help pages across projects. This wikitext contains template tags of the form "{{h:rest of name }}" which allow project-specific content within help pages, using project-specific templates.

Template names referred to by such tags are reserved, follow the link Template:h:f to see the full template name in this project in the case that rest of name is "f ":

  • for English projects with case-insensitivity of the first character: template names starting with "Template:H:".
  • for other projects with case-insensitivity of the first character: template names starting with "Vorlage:H:" and "Modèle:H:", etc.
  • for projects with case-sensitivity of the first character: template names starting with "Template:h:", "Vorlage:h:", "Modèle:h:", etc.
  • for Hebrew "H:rest of name :" comes to the left of the Hebrew word for template תבנית , see he:Template:h:f, except that if rest of name is the empty string than ":H:" instead of "H::" comes to the left of תבנית , see he:Template:h:. The reserved names are those of which the canonical form of the URL starts with "http://he.wikipedia.org/wiki/%D7%AA%D7%91%D7%A0%D7%99%D7%AA:H:" and similar for the other Hebrew projects.

Note that "case-insensitivity of the first character" refers to the first character after the first colon, not after the second.


Examples

  • Template:Tiw - message
  • Template:Tiw
  • Template:Tiw
  • templates with many parameters and images depending on {{PAGENAME}}:
    • Template:Tiw
      • {{PAGENAME}}_flag_large.png
      • {{PAGENAME}}_coat_of_arms_large.png
      • Location{{PAGENAME}}.png
    • Template:Tiw
      • {{PAGENAME}}_flag_medium.png
      • {{PAGENAME}}_armoirie.png
      • Location{{PAGENAME}}.png
    • Template:Tiw
  • Template:Tiw - small, often used image
  • Template:Tiw - translation
  • Template:Tiw - intermediate template for translating the parameter names, containing e.g. "superficie = {{{area}}}"
  • Template:Tib
  • Template:Tib
  • Template:Tim - calls one of several templates, dependent on namespace
  • Template:Tiw - calls one of many templates, depending on pagename.
  • Template:Qotd - quote of the day - the content of the template is changed daily
  • Template:Tic - picture of the day - the pictures can be prepared in advance, because the template shows an image, depending on {{CURRENTYEAR}}, {{CURRENTMONTH}}, and {{CURRENTDAY}}, and, for the caption, calls one of many templates, depending on these and also on a parameter for the language; unlike the quote of the day above, the rendered image is changed at the fixed time of 0:00 UTC.
  • article of the day on the English Wikipedia: see list - included as a template on the main page.

See also

Template:H:

Template:H:f