Help:Template
This help page is a how-to guide. It explains concepts or processes used by the Wikipedia community. It is not one of Wikipedia's policies or guidelines, and may reflect varying levels of consensus. |
A template is a Wikipedia page created to be included in other pages. Templates usually contain repetitive material that might need to show up on a larger number of articles or pages. They are commonly used for boilerplate messages, standardized warnings or notices, infoboxes, navigational boxes, and similar purposes. Templates can have parameters so that the same page generates different text on multiple pages that include it.
The most common method of inclusion is called transclusion, where the wiki source of the target page contains a reference to the template, using the {{Template name}}
syntax. Another method is substitution, where the content of the template is copied into the wiki source of the target page, just once, when it is saved.
Help:A quick guide to templates gives a brief introduction to the subject. There is further help from MediaWiki and Wikimedia at mw:Help:Templates, m:Help:Template, and m:Help:Advanced templates.
General description
Most templates are in the template namespace, which means that they have titles in the form "Template:XXXX". It is possible, however, to transclude and substitute from any namespace,[a] and so some template pages are placed in other namespaces, such as the user namespace. Template pages have associated talk pages.
Templates can contain any desired wikitext, including calls to other templates. There is some programming ability: customizable values (via parameters); calculation and branchings (using parser functions); and access to wiki-specific variables (magic words), such as dates, times, and page names. They may also contain markup to define certain parts of the page to be included while other parts are not. This means that when you display the template page itself, you may see more than when you display a page that includes it (for example, it can contain documentation, categories, etc. for the template).
To call a template (cause it to be transcluded or substituted in the page), a page contains wikitext in double braces. For example, the wikitext {{under construction}}
calls the {{under construction}} template. Sometimes the call includes parameters and looks like {{under construction|comment=This is a comment}}
. Note that template calls are not the only thing for which double braces are used in wikitext.
Note that while templates are the usual way transclusion and substitution happen on Wikipedia, they are not the only way.
Using templates
General
Using a template is much like calling a function in a programming language – call it, and it returns a value. For a template, the return value is called the expansion of the template and is treated as part of the calling page source. Like functions, some templates accept parameters that affect the output.
Calling a template causes it to be either transcluded or substituted in the page that calls it (which is known as the target page).
Transcluding a template means that when MediaWiki displays the page, it treats the template as if it were in the wiki source of the page, whereas substituting means MediaWiki does that when it saves the page (i.e. the content of the template gets stored as part of the target page and subsequent editors cannot tell that it got there via a template).
To transclude a template into a page, put {{Template name}}
in the page source at the place where the template is to appear. The first letter of each word of the title may equivalently be lower- or upper-case.
To substitute a template into a page, use {{subst:Template name}}
instead.
This wikitext is called a template call.
In MediaWiki, the wiki software that Wikipedia uses, variables are distinct from templates, but they are both identified by double braces {{ }}
and they both return a value.
Whereas MediaWiki variable names are all uppercase, template names have the same basic features and limitations as all page names: they are case-sensitive (except for the first character); underscores are parsed as spaces; and they cannot contain any of these characters: # < > [ ] | { }
. This is because those are reserved for wiki markup.
The number sign #
denotes a fragment identifier, which identifies a fragment or section of a document (such as a section in a Wikipedia article). Although you can use it in a link to link to a section of a template page (like Template:Portal#Example), fragment identifiers have no meaning in a template call and are ignored. For example, {{Portal#Location|Books}}
is the same as {{Portal|Books}}
.
The template namespace is the default, so you can leave out the namespace Template:
in the template name, and it is conventional to do so. However, you must specify the namespace prefix for templates in other namespaces, such as User:
. To transclude a page in mainspace, precede its title with a colon, as {{:Page name}}
.
Note: Attempting to transclude a template that does not exist produces a red link, just like linking to any other nonexistent page. Following the link allows one to create that particular template. It is not possible to transclude pages between projects (such as different-language Wikipedias or MediaWiki)—to use a template on another language project, a copy of the template must be created in that project.
Parameters
The basic transclusion syntax given above can be extended with parameters, which are used to control the template's output. The syntax for this is
{{Template name|parameter|parameter|...}}
where Template name
is the name of the template, and each parameter
may either contain just a value (these are called unnamed parameters) or be of the form name=value
(named parameters). The first, second, third, etc. unnamed parameters are given the names 1
, 2
, 3
, etc.
Whitespace characters (spaces, tabs, returns) are stripped from the beginnings and ends of named parameter names and values, but not from the middle: thus {{ ... | myparam = this is a test }}
has the same effect as {{ ... |myparam=this is a test}}
. This does not apply to unnamed parameters, where all whitespace characters are preserved.
What parameters (if any) can or should be passed to a template and how they are to be named is defined in the coding of that template. A template call can specify named parameters in any order. Superfluous or misnamed parameters are ignored; unspecified parameters are assigned default values. If a parameter is specified more than once, the last value takes effect.
The value of a parameter can be the empty string, such as when the pipe or equals sign is followed immediately by the next pipe or the closing braces. This is different from not specifying the parameter at all, which results in a default value, although templates are often coded so as to behave the same in both cases.
If a template call specifies a parameter which is not defined in the template, it has no effect. Sometimes editors do this on purpose: For example, |reason=
is frequently used as a pseudo-parameter to explain briefly in the wiki source why the template call was put there.[b] Some templates use {{#invoke:check for unknown parameters|check|...}}
to warn the editor if a parameter is being used that is not accounted for in the template's code; this is mostly used for infoboxes and other templates with a large number of complicated parameters, where the presence of an unknown one is usually an unintentional error. If you update such a template to define a new parameter, its call to the module must also be updated to include the new parameter.
Wikitext syntax does not allow natively to create truly variadic templates, but only pseudo-variadic ones, that check the incoming parameters one by one until a certain fixed amount. It is possible to break this limitation however by using dedicated modules. For simple cases, {{#invoke:separated entries|main}}
allows to expand all sequential parameters blindly and has the ability to set custom delimiters. For more complex cases, {{#invoke:params}}
allows to count, list, map, filter and propagate all incoming parameters without knowing their number in advance.
Examples
Note: If you wish to experiment with any of these, you can use the template sandbox or your user page or sandbox. You can try out your template with Special:ExpandTemplates.
An example of a very simple template can be found at Template:TM, which expands to wikitext that places the trademark symbol (™), linked to the trademark article, at that point in the displayed page. A programmer would say that the template "returns" the trademark symbol link wikitext.
Display Template:TM (by clicking on the foregoing link), then click on the "Edit" tab to see the template code (its page source). The active part of that code, which becomes the expansion of the template when it is transcluded, is the single link wikitext [[Trademark|™]]
. The remainder of the page source is enclosed between <noinclude>
tags, so it shows up when you display the template page itself but not when you display a page that calls the template.
To transclude Template:TM onto another page (i.e., to use it on another page), type {{TM}}
into the source of that page (the target page) and click Show preview. The page will be displayed with the template call replaced by the expansion of the template, as if the wikitext actually contained [[Trademark|™]]
at that point. The displayed page will therefore contain the wikilink "™".
For example, type The trademark symbol is {{TM}}
and you will see "The trademark symbol is ™" when previewing the page or after saving the change.
The other way to use a template is to substitute it. If you type The trademark symbol is {{subst:TM}}
and preview or save the page, you will see "The trademark symbol is ™" just as with the transclusion example above. But if you save the page and then look again at the saved page source,[c] you will see The trademark symbol is [[Trademark|™]]
, because the template call was replaced by the expansion of the template when you saved the page. There is no ongoing connection to the template call; no one can tell by looking at the page source that you didn't just type The trademark symbol is [[Trademark|™]]
and if the {{TM}} template changes (or ceases to exist), your page will continue to display as it does now. (In contrast, in the transclusion example above, if the {{TM}} template subsequently changes, your page may then display differently).
Examples with parameters
An example of a template that takes parameters is the template {{about}}
. Try typing {{about|how to use templates|how to use modules|Help:Lua}}
in the sandbox—it will produce the following text:
The template {{about}}
uses three unnamed parameters (also called positional parameters) in the example above, but you can call the same template with different numbers of parameters to give slightly different results, as explained in the template's documentation. For example, {{about||how to use modules|Help:Lua}}
. Note the usage of an empty parameter—in this instance, the consecutive pipes mean that the first parameter specified is an empty string, which in this template will cause it to omit the initial "about" sentence. This produces:
A simple example of a template that has named parameters is Template:Payoff matrix, used to generate a 2-by-2 grid. For example:
Markup | Renders as | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
{{payoff matrix | UL = 5 | UR = 7 | DL = 2 | DR = 9 | Name = Example usage }} |
| ||||||||||||
See the template page for more possibilities. Notice that the template is called here without specifying all its possible parameters, so undefined parameters are given default values.
Hints and workarounds
The following points may be worth noting when using templates:
- Templates are not the only method of transclusion, in some cases, other methods such as selective transclusion are more appropriate.
- An unnamed parameter (positional parameter) value cannot contain an ordinary equals sign, as this would be interpreted in the parameter specification as a named parameter (with the equals sign separating the name from its value).[d]
- To specify an unnamed parameter including an equals sign (for example in a URL with name–value pairs), replace the equals sign with the magic word
{{=}}
, which expands to an equals sign that will not be interpreted. - Another method is to explicitly specify the positional parameters. The first unnamed parameter is named "1" and so on. To call template {{done}} with
a=b
as the literal value for the first parameter, type either{{done|a{{=}}b}}
or{{done|1=a=b}}
.
- To specify an unnamed parameter including an equals sign (for example in a URL with name–value pairs), replace the equals sign with the magic word
- Similarly, it is not possible to use an ordinary pipe character
|
in a template parameter specification, as it would be interpreted as separating one parameter specification from another.[e] This problem can similarly be solved by using the magic word{{!}}
in place of the pipe, or—if the pipe is not intended to be parsed at a higher level—using the HTML entity|
. Alternatively, for embedding wikitables in templates, you may use{{Wikitable}}
to avoid excessive{{!}}
. - Remember that whitespace characters (spaces, tabs, carriage returns, and line feeds) are not automatically stripped from the start and end of unnamed parameters, unlike with named parameters. Including such characters (or any other non-visible characters in any parameters) may in some cases affect the template's behavior in unexpected ways. (Template designers can use {{Trim}} to remove unwanted whitespace in unnamed parameters).
- In documentation and discussions, it is customary to put the name of a template in double braces to emphasize the reference to a template (for example, use {{Trim}} as the name of Template:Trim). If you just type
{{Trim}}
in the source page, that will of course call the template, so to make it easy to display the name with the braces, and also make the name a link to the template for the reader's convenience, there is the {{tl}} template (the "template link" template). For example,{{tl|Example}}
produces {{Example}}. There are various other template-linking templates available with other functions. - When an editor changes a template (by editing the template or one of its subtemplates), the change will ultimately be reflected any time any page that transcludes that template is subsequently displayed. However, the change may not become visible on all pages immediately; a previously cached version of a page, based on the previous version of the template, may continue to be displayed for some time. Use the purge function to force a page to be displayed using the latest versions of templates—including on the template page itself, if it contains usage examples.
- When viewing old versions of pages, remember that templates will be transcluded as they are now, not necessarily as they were when the old page version was active.
- To list all pages that transclude a template, use the What links here link on the page when you display the template page. Note that this will not include pages where the template has been substituted, as there is no record of substitutions.
- To get a list of templates transcluded on a page, bring up the edit page and find the list below the edit window. This list also includes the subtemplates used by the templates that are directly transcluded. To get such a list for a page section, an old version of the page,[f] or your newly edited version prior to saving, click Show preview on the appropriate edit page.
- There are limits to the number and complexity of the templates that an article may have. See the "§ Expand limits" section for help with this.
- If you want the template to leave a time stamp or signature, you can write
<noinclude><nowiki></noinclude>~~~~~<noinclude></nowiki></noinclude>
, but this works only when you substitute the template. If you transclude it, you'll just get ~~~~~. - To improve readability, programmers usually like to split code with newlines and indent it. Unfortunately, MediaWiki does not allow this technique; in many instances, these purpose-built newlines are treated by MediaWiki as content. One possible workaround is to add
<!--
before each newline character and-->
after it, which produces an HTML comment.
Writing templates
Process
Templates are just Wikipedia pages. They are created, deleted, and edited in much the same way as any other page.
Creating
To create a template, choose an appropriate name, navigate to that page, then click the "Edit" tab or create a new page as needed.
Templates are normally placed in the template namespace, though you can place a template intended for your own personal use or for experimentation in your own user space.
Before creating a template, do a quick search for existing templates (such as by exploring Category:Wikipedia templates) to see if there is already a template that does what you want or a similar template whose code can be copied and modified (or left in place and expanded). Look for generic templates on which the new template can be based; for example, you can create a navbox template easily by creating a brief template that calls the generic Template:Navbox.
There is no hard rule about what name to choose for a template—make it short but reasonably descriptive. The naming guideline says: "Template function should be clear from the template name". If similar templates exist, try to follow a consistent naming pattern. You can rename a template without breaking existing transclusions (what is called breakage) by leaving a redirect to the new template name.
Modifying
Edit a template the same way as any other page: navigate to the template and click the "Edit" tab.
Be extremely careful when editing existing templates—changes made can affect a large number of pages, often in ways you might not expect. For this reason many high-use templates are protected against editing except by administrators and template editors; other editors can propose changes on the talk page. Some templates offer a sandbox and test cases for experimentation.
Deleting
Unused or inappropriate templates should be deleted. Templates that can be easily merged into another should be merged.
To propose the deletion or merger of a template, go to Templates for discussion (TfD).
Coding a template
Anything that can be included on a normal page or article can be included on a template, including other templates (called subtemplates). Templates often make use of programming features—parameters, parser functions, and other magic words—which allow the transcluded content to vary depending on context. There are also special tags to control which information is transcluded and which is not.
Metatemplates
Various metatemplates and metamodules exist to help accomplish common template tasks. They are called like normal templates and modules, but they serve a purpose that makes writing templates easier. See Category:Wikipedia metatemplates and Category:Template metamodules for a list of those templates and modules.
Handling parameters
In template code, the value of a parameter is represented by items enclosed between triple braces, which is a parameter reference.
- The code
{{{xxx}}}
expands to the value of the parameter named "xxx". - The codes
{{{1}}}
,{{{2}}}
, and so on are expanded to the first, second, and so on unnamed parameters. (Note that an unnamed parameter can alternatively be specified in a template call as an equivalent named parameter named "1", "2", etc.).
If a parameter is not specified in the template call, then the parameter reference is not replaced with anything -- it is expanded literally; this means that if the template call does not specify the parameter "xxx", the wikitext {{{xxx}}}
inside the template expands to literally {{{xxx}}} (not the null string you may have expected). You can get a more useful behavior by specifying a default value in the parameter reference. Do this with the pipe syntax: {{{xxx|dflt}}}
specifies the default value dflt
for the named parameter "xxx", and {{{1|dflt}}}
specifies the default value dflt
for the first unnamed parameter. Most often, one specifies a null default value, such as {{{1|}}}
or {{{xxx|}}}
.
You can use default parameter values to effect a parameter alias:
For example, if parameters "text" and "message" are names for the same parameter, which can also be specified as the only unnamed parameter, then refer to the parameter with {{{message|{{{text|{{{1|}}}}}}}}}
. If the template call specifies more than one of those parameters, "message" will have priority, followed by "text", and finally by the first unnamed parameter. So if a template call specifies parameters |message=A|text=B|C
, the above wikitext expands to A
.
Because of the multiple meanings of double-brace and triple-brace syntax in wikitext, expressions can sometimes be ambiguous. It may be helpful or necessary to include spaces to resolve such ambiguity. For example, {{ {{{xxx}}} }}
or {{{ {{xxx}} }}}
, rather than typing five consecutive braces, may be more human-readable. But watch out for unwanted whitespace appearing in the template expansion.
Parameter references do not get expanded when they are wrapped in <nowiki>
tags.
Example
The parameter usage example above refers to the {{payoff matrix}} template. Here is the code in the template that implements those parameters:
{| id="Payoff matrix" style="background:white; float: {{{Float|right}}}; clear:right; text-align:center;" align={{{Float|right}}} cellspacing=0 cellpadding=8 width={{{Width|225}}}
|-
|style="width:33%; "|
|style="width:33%; border-bottom: solid black 1px;"| {{{2L|Left}}}
|style="width:33%; border-bottom: solid black 1px;"| {{{2R|Right}}}
|-
|style="border-right: solid black 1px; text-align: right; "| {{{1U|Up}}}
|style="border-right: solid black 1px; border-bottom: solid black 1px; background:{{{ULc|white}}}; font-size:120%; "| {{{UL|0, 0}}}
|style="border-right: solid black 1px; border-bottom: solid black 1px; background:{{{URc|white}}}; font-size:120%; "| {{{UR|0, 0}}}
|-
|style="border-right: solid black 1px; text-align: right; "| {{{1D|Down}}}
|style="border-right: solid black 1px; border-bottom: solid black 1px; background:{{{DLc|white}}}; font-size:120%; "| {{{DL|0, 0}}}
|style="border-right: solid black 1px; border-bottom: solid black 1px; background:{{{DRc|white}}}; font-size:120%; "| {{{DR|0, 0}}}
|-
|style="font-size: 90%;" colspan=3 |''{{{Name|{{PAGENAME}}}}}''
|}
The entity {{{2L|Left}}}
instructs the template to use the value of the named parameter 2L
or the text Left
if the parameter is not specified in the call.
Special case: parameters within an XML-style opening tag
Parameter references aren't expanded inside XML-style opening tags. Thus, the following will not work within a template:
- <ref name={{{param}}}> Smith, Adam (1776)...</ref>
because the parameter is not expanded. Instead, you can use the {{#tag:}}
parser function, which is—for example—used in {{sfn}}
to generate the <ref>...</ref>
element; see also Help:Magic words § Formatting. Therefore, the following example will work:
- {{#tag:ref | Smith, Adam (1776)... | name={{{param}}} }}
Caution: overextending URLs
If a parameter's value is (or ends with) a URL, check whether it is displayed in Wikipedia with the link overextending by one or more characters after the URL so that clicking the link causes an error or failure.
This could happen because the source code does not have a space after the URL or it contains or generates a space that is discarded in the processing. Ensure that in the template expansion a soft space (not a hard or non-breaking space) follows the URL, regardless of whether you or a user supplied the URL or whether it was generated by automated processing. The {{spaces}}
template may be useful.
System variables and conditional logic
Template code often makes use of the variables and parser functions described at Help:Magic words to make the template's behavior depend on the environment in which it is included (such as the current time or namespace). Parser functions can be used for some arithmetic calculations and string manipulations on variables and parameter values, but certain standard programming features such as loops and variable assignment are not available. Full string manipulation not available; some templates providing such function have been created, but they are inefficient and imperfect.
Some of the most frequently used variables and functions are listed below. For more, see Help:Magic words and the fuller documentation at the MediaWiki pages mw:Help:Magic words and mw:Help:Extension:ParserFunctions.
Description | wiki source | Displayed text |
---|---|---|
Uppercasing text | {{uc: Heavens to BETSY! }}
|
HEAVENS TO BETSY! |
Lowercasing text | {{lc: Heavens to BETSY! }}
|
heavens to betsy! |
Getting a namespace name | {{NS: 1 }}
|
Talk |
Getting a Wikipedia URL | {{fullurl: pagename }}
|
//en.wikipedia.org/wiki/Pagename |
The ParserFunctions extension provides more programming-oriented parser functions:
Description | Wiki source | Displayed text |
---|---|---|
Testing for equality between two strings (or parameters) | {{#ifeq: yes | yes | Hooray...! | Darn...! }}
|
Hooray...! |
{{#ifeq: yes | no | Hooray...! | Darn...! }}
|
Darn...! | |
Testing whether a string (or parameter) contains anything (other than whitespace) | {{#if: {{{param|}}} | Hooray...! | Darn...! }}
|
Darn...! |
Making a calculation (mathematics) [area of circle of radius 4, to 3 decimal places] |
{{#expr: ( pi * 4 ^ 2 ) round 3 }}
|
50.265 |
Testing the result of a calculation [is 1230 even or odd?] |
{{#ifexpr: 1.23E+3 mod 2 | Odd | Even }}
|
Even |
Description | Wiki source | Displayed text (for this help page) |
---|---|---|
Page names | {{PAGENAME}}
|
Template |
{{FULLPAGENAME}}
|
Help:Template | |
Name of the current namespace | {{NAMESPACE}}
|
Help |
Number of registered users | {{NUMBEROFUSERS}}
|
48,021,346 |
Number of pages in a given category | {{PAGESINCATEGORY:"Weird Al" Yankovic albums}}
|
19 |
Current software version | {{CURRENTVERSION}}
|
1.43.0-wmf.23 (a5827e3) |
Timestamp of last revision | {{REVISIONTIMESTAMP}}
|
20240913194158 |
The {{PAGENAME}}
and {{NAMESPACE}}
variables are particularly useful, and frequently used, to change template behavior based on the context in which they are included. Templates that contain category links often do this. For example, a cleanup template contains a category link to categorize the calling page as one which needs cleanup, so the template is likely to condition that category link on the {{NAMESPACE}}
variable so that talk pages, user pages, and any other pages that might call the template incidentally do not get categorized as pages needing cleanup.
Nesting templates
A template may call another template—this is called nesting and the called template is called, in this context, a subtemplate. When WikiMedia expands the template, it expands subtemplates as the calls to them appear, so that the final product is essentially the result of expanding templates from the most deeply nested out.
While fairly straightforward in application, it involves some noteworthy quirks and tricks.
To pass a parameter value from a template call to to a subtemplate, use a parameter reference in the template call to the subtemplate.
- Example:
- Template:A contains
"the quick brown {{B|{{{3}}} }} jumps over..."
. Template:B (a subtemplate) contains'''{{{1}}}'''
. Page X calls A with{{A|apple|pear|fox}}
This expands to"the quick brown '''fox''' jumps over..."
. The third unnamed parameter passed to Template:A gets passes as the first unnamed parameter to subtemplate B.
A template can even choose which subtemplate parameter to pass conditionally.
- Examples:
- Template:A contains
the quick brown {{B|{{{3}}}=fox}} jumps over...
. Template:B (a subtemplate) contains'''{{{jumper}}}'''
. Page X calls A with{{A|apple|pear|jumper}}
. This expands to"the quick brown '''fox''' jumps over..."
. The third unnamed parameter passed to Template:A is passed as the name of the parameter passed to subtemplate B with the value "fox".
Template recursion is not available; that is, a template may not call itself directly, or indirectly by calling other templates which call it. Attempts to do so will result in an error message describing a "template loop".
When a subtemplate contains unmatched braces—as in {{lb}}}
—the unmatched braces are treated as text during processing—they do not affect the parsing of braces in the calling template. But where the template is substituted, the unmatched braces will be parsed as braces when the page is subsequently displayed. This has little practical use, but can occasionally introduce unexpected errors.
See m:Help:Advanced templates and m:Help:Recursive conversion of wikitext for more information.