Powered by
TTSReader
Share this page on
Article provided by Wikipedia


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 any number of articles or pages. They are commonly used for "boilerplate messages, standard warnings or notices, "infoboxes, "navigational boxes and similar purposes.

The most common method of inclusion is called "transclusion, where the "wikitext 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 wikitext 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.

Contents

General description[edit]

""
A basic overview of how templates work (8 minute video)

Most templates are pages 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,[1] 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. They have some limited programming capacities: customizable values (called 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 tags which define which parts of the wikitext are to be included when the template is transcluded or substituted. This means that the appearance of the template page itself need not be the same as that of the transcluded content (for example, it can contain documentation, categories, etc. for the template).

How to do it: To transclude a template into an article or page, type {{template name}} in the wikitext at the place where the template is to appear. The first letter may be indifferently lower- or upper-case.

The prefix Template: before the template name is the default one and need not be included. However, for templates stored in other namespaces, the prefix, such as User:, must be specified. 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)—to use a template on another language project, a copy of the template must be created in that project.

Usage syntax[edit]

Parameters[edit]

The basic transclusion syntax given above can be extended by the addition of "parameters, which are used to control the template's output. The syntax for this is

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

Which parameters (if any) can or should be passed to a template and how they are to be named depends on the coding of that template. Named parameters can be defined in any order. Superfluous or misnamed parameters will be ignored; undefined parameters will be assigned default values. If a parameter is defined more than once, the last value takes effect.

The value of a parameter can be the empty string (pipe or equals sign followed immediately by the next pipe or the closing braces). This is different from omitting the parameter altogether, which leaves it undefined, although templates are often coded so as to behave the same in both cases.

Parameters can be specified (and will do nothing) even if not represented in the template's code. For example, |reason= is frequently used as a pseudo-parameter to explain briefly in the wikisource why the template was placed. (Some templates, e.g. {{"rm}}, have code to display |reason= as visible output; whether to do so is determined on a template-by-template basis.) Some templates call "Module:Check for unknown parameters to warn the editor if a parameter is being used that isn't 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 include a new parameter, its call to the module must also be updated to include the new parameter.

Calling[edit]

Calling a template is not unlike calling a "variable or a "function in a programming language: call it with a reference, and it returns a value (the "output). Like functions, some templates accept parameters that change the output.

In "MediaWiki—the "wiki software that Wikipedia uses—"variables have a more specific meaning that distinguishes them 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 can't contain any of these characters: # < > [ ] | { } (because those are reserved for "wiki markup and "HTML).

The "number sign # is called a "fragment identifier because it denotes a fragment or section of a document (such as a "section in a Wikipedia article). Although it "can be used to link to a section of a template page (like "Template:Portal#Example), there is no reason to put a fragment identifier or fragment name in a template reference. In {{Portal#Location|Books}}, for example, the string #Location has no purpose, and is effectively ignored.

Substitution[edit]

When a template is "substituted, its content is "hard-coded in the page rather than "transcluded. To learn how and when to substitute a template, see "Help:Substitution to learn "when and how to use substitution.

Basic template usage examples[edit]

If you wish to experiment with any of these, please use the "template sandbox, your user page or sandbox

An example of a very simple template can be found at "Template:Lambda, which expands out to place the lambda symbol ( λ) at that point in the text. A programmer would say that the template returns the lambda symbol ( λ).

Click on "Template:Lambda then click on the "Edit source" tab to see the template code (its wikitext). The "active" part of that code, called the expansion of the template, is the single word &lambda;. (&lambda; is the "HTML character entity for the Greek letter ( λ).) The remainder of the wikitext is enclosed between <noinclude>...</noinclude> tags so it is displayed on the template page itself but will not be displayed when the template is used (or called) on another page.

To transclude the Template:Lambda onto another page (i.e. to use it on another page), type {{lambda}} (or {{Lambda}}—the case of the first letter is not significant) into the wikitext of the target page and 'show preview'. The page will be displayed with the template call were replaced by the expansion of the template. i.e. as if the wikitext actually contained &lambda; at that point. The displayed page will therefore contain the text "λ".

For example, type "The 11th letter of the Greek alphabet is the lambda ({{lambda}})" and you will see "The 11th letter of the Greek alphabet is the lambda (λ)". You can use templates without knowing the details of their code—you only need to remember what result they produce (this is usually described on the template page).

Another way to use this template is to "substitute it. If you type "The 11th letter of the Greek alphabet is the lambda ({{"subst:"lambda}})" and save the page, you will again see "The 11th letter of the Greek alphabet is the lambda (λ)". However this time, if you look again at the saved wikitext, you will see that the template calls really were replaced by the expansion of the template when you saved the page. The link between the output text and the template is now broken, and the output will not be affected by future changes to the template (as it would be in the case of transclusion).

Examples with parameters[edit]

An example of a template that takes parameters is the template {{"about}}. Try typing {{about|how to use templates|how to use modules|Help:Module}} in the sandbox—it will produce the following text:

The template {{"about}} uses three unnamed parameters in the example above, but the same template can also be used with different numbers of parameters to give slightly different results, as explained in the documentation on the template page. For example, {{about||how to use modules|Help:Module}}.

Note the usage of an empty parameter—in this instance, the consecutive pipes mean that the first parameter that was "passed" to the template is an empty string, which in this template will cause it to omit the initial "about" sentence. This produces:

Other templates, particularly more complex ones, take named parameters or a mixture of named and unnamed ones. A simple example is "Template:Payoff matrix, used to generate a 2-by-2 grid. Type:

{{payoff matrix | UL = 5 | UR = 7 | DL = 2 | DR = 9 | Name = Example usage }}
Left Right
Up 5 7
Down 2 9
Example usage

to produce the grid you can see on the right.

See the "template page for more possibilities. Notice that the template is used here without defining all its possible parameters—undefined parameters are given default values.

The spaces around the equal signs and before and after the parameters are used only for clarity—they are not needed and are ignored when the template is evaluated (although this is not the case with unnamed parameters). However parameter names are fully case sensitive—for example, it is not possible to replace "DR" by "dr" or "dR" in the above example. Parameters with names that are not used by the template are simply ignored.

Examining the source code of the template shows the standard table mark up with some extra triple bracket entities representing the 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}}} means use the named parameter 2L, or the text 'Left' if the parameter is not present in the call.

Usage hints and workarounds[edit]

The following points may be worth noting when using templates:

Creating and editing templates[edit]

Templates are created and edited in much the same way as any other page: choose an appropriate name, navigate to that page, then click the Edit tab or create a new page as needed. As mentioned above, templates are normally placed in the "Template namespace, though templates intended for your own personal use or for experimentation can be created in your own "user space. 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.

Before creating a template, do a quick search for existing templates (e.g. by exploring "Category:Wikipedia templates) to see if there's 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, "navbox templates can be easily created by calling the generic "Template:Navbox).

There is no hard rule about what name to choose for a template—make it short but reasonably descriptive. If similar templates exist, try to follow a consistent naming pattern. Templates can be renamed without breaking existing transclusions, provided a redirect to the new template name is left behind.

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.

To propose the deletion or merger of unused or inappropriate templates or templates that can easily be merged, go to "Templates for discussion (TfD).

Handling parameters[edit]

The values of the parameters which can be fed to a template are represented in the template code by items enclosed between triple braces:

If a parameter is not assigned a value, then no replacement will take place—this means that if no value is passed for parameter xxx, the value of the expression {{{xxx}}} inside the template will literally be {{{xxx}}} not the 'blank' you may have expected. A more intuitive behaviour can be achieved by specifying default parameter values. This is done 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, this is used to specify null default values ({{{1|}}} or {{{xxx|}}}).

Note the default text must be real text: that you cannot assign another parameter as the default. It will simply return the 'name' of the parameter as text.

Because of the multiple uses of double-brace and triple-brace syntax, expressions can sometimes be ambiguous. It may be helpful or necessary to include spaces to resolve such ambiguity, for example by writing {{ {{{xxx}}} }} or {{{ {{xxx}} }}}, rather than typing five consecutive braces. However, watch out for unwanted whitespace appearing in template expansions.

Special case: Parameters within XML-style opening tag

Parameters do not get expanded when they are wrapped in <nowiki>...</nowiki> tags. They however aren't expanded either if placed within the actual "XML-style opening tag. 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 however use the {{#tag:}} "parser function, which for example is used in {{"sfn}} to generate the <ref>...</ref> element (see also "Help:Magic words#Formatting) Therefore, the following example will work:

{{#tag:ref | Marx, Karl (1848)... | 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. Ensure that, after processing by the software, a soft space (not "hard or nonbreaking) follows the URL, regardless of whether you or a user supplied the URL, or it was generated by automated processing. Possibly, the source code could contain or generate a space that is discarded in the processing or there might not be any space there. Correct the source code, perhaps by forcing a soft space to appear after the URL. The {{"Spaces}} template may be useful.

System variables and conditional logic[edit]

Template code often makes use of the variables and parser functions described at "Help:Magic words, in order to make the template's behaviour depend on the environment (such as the current time or namespace) or on the parameter values that are passed to it. They can also be used for arithmetical calculations but certain standard programming features such as loops and variable assignment are not available. Full string manipulation is also not available (some templates providing such functionality have been created, but they are inefficient and imperfect).

Some of the most often 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.

Examples of core parser functions
Description Text entered Result
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.

Examples of extension parser functions
Description Text entered Result
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
Examples of system variables
Description Text entered Result (for this help page)
Page names {{PAGENAME}} Template
{{FULLPAGENAME}} Help:Template
Name of the current namespace {{NAMESPACE}} Help
Number of registered users {{NUMBEROFUSERS}} 33,663,411
Number of pages in a given category {{PAGESINCATEGORY:"Weird Al" Yankovic albums}} 20
Current software version {{CURRENTVERSION}} 1.32.0-wmf.4 (03a6eac)
Timestamp of last revision {{REVISIONTIMESTAMP}} 20180403151131

The PAGENAME and NAMESPACE variables are particularly useful, and frequently used, to change template behaviour based on context. For example, if the template transcludes a category link (e.g. cleanup templates, which transclude a link categorizing the page as a page which needs cleanup), it will often check the NAMESPACE variable to make sure that talk pages, user pages or anywhere else the tag might incidentally be placed do not themselves get categorized as pages needing cleanup.

Nesting templates[edit]

Templates may contain other templates—this is usually called "nesting". As the template is processed, the wikitext produced by any nested templates is transcluded into the nesting template, so that the final product is essentially processed from the most deeply nested template out. While fairly straightforward in application, it involves some noteworthy quirks and tricks.

To pass a parameter value to a nested template, place a parameter tag as the value of one of the nested template's parameters.

Template parameters themselves can be chosen conditionally.

"Shortcut

A template can call itself but will stop after one iteration to prevent an infinite loop.

When a nested template contains unmatched braces—as in {{"lb}}}—the unmatched braces are treated as text during processing, and do not affect the parsing of braces in the nesting template. If the nested template is substituted, however, the substitution is processed first, and this will change how braces are parsed in the nesting template. This has little practical use, but can occasionally introduce unexpected errors.

See the meta:Help:Advanced templates and meta:Help:Recursive conversion of wikitext for more information. These pages also contain information on unusual calls such as {{template {{{parameter|}}} }}.

Noinclude, includeonly, and onlyinclude[edit]

"Shortcuts

By default, when a template is transcluded (or substituted), the entire wikitext (code) of the template page gets included in that of the target page. However it is possible to modify that behaviour, using tags that specify which parts of the template code are to be included. This makes it possible to avoid transcluding information intended for display only on the template page itself, such as the template's documentation, "categories and "interwiki links. It is also possible to have parts of the code be transcluded, but not be processed on the template page itself (e.g. categories to be applied to the target pages which do not apply to the template). The tags are as follows

Wikitext What is rendered here (source page) What is transcluded there (destination page)
<noinclude> text1 </noinclude> text2 text1 text2 text2
<onlyinclude> text1 </onlyinclude> text2 text1 text2 text1
<includeonly> text1 </includeonly> text2 text2 text1 text2

Perhaps the most common issue with the use of these blocks is unwanted spaces or lines. It is important to remember that the effect of these tags begins immediately before the first angle bracket, not on the previous line or at the previous visible character; similarly the effect ends immediately after the last angle bracket, not on the next line or with the next visible character.

Examples
  1. }}<includeonly>
    }}
    <includeonly>
  2. }}<noinclude>
    }}
    <noinclude>
  3. {{template}}</includeonly><noinclude>
    {{template}}</includeonly>
    <noinclude>

These tags can be nested inside each other, though (for a given page) this really only applies to the <onlyinclude> tag; nesting <includeonly> and <noinclude> tags is fairly pointless. Be careful not to split the tags, however. Constructions like <onlyinclude>abc<includeonly>def</onlyinclude>ghi</includeonly> will not work as expected. Use the "first opened, last closed" rule that is standard for XML.

Problems and workarounds[edit]

Documentation[edit]

Categorizing your template and documenting its proper usage will make it easier for other editors to find and use.

Documentation for users, together with the template's categories, is normally placed after the template code, inside <noinclude>...</noinclude> tags. It is normally necessary to put the opening <noinclude> tag immediately after the end of the code, with no intervening spaces or newlines, to avoid transcluding unwanted whitespace.

In the case of complex templates, the documentation (together with categories) is often kept on a separate "subpage of the template page (named "Template:XXX/doc"). This also applies to many "protected templates (to allow the information to be edited by non-administrators). This is achieved by placing the {{"Documentation}} template after the main template code (within <noinclude>...</noinclude> tags). If the "/doc" subpage does not exist, a link will then appear enabling it to be created.

Categorization[edit]

Categorize pages by template inclusion[edit]

Some templates contain category definitions in their transcluded code, i.e. they are intended to place the target pages in particular categories. This is often done with maintenance categories (placing articles into ordinary content categories in this way is discouraged). When doing this, it may be necessary to use <includeonly>...</includeonly> tags to keep the template itself out of the category. While developing, testing, sandboxing, or demonstrating a template intended to apply a category, either temporarily replace each category with a test category (starting with "X1, "X2, or "X3) or suppress categorization (see "category suppression in templates).

Categorize templates[edit]

Categorization declaration [[Category: Some-topic templates ]] should be placed on the template's documentation page (or inside <noinclude>...</noinclude> tags, if there is no documentation page) to avoid polluting the transcluding pages.

Aliases[edit]

Aliases can be created with "redirects. For example, "Template:Tsh redirects to "Template:Template shortcut. Then you can write {{"tsh|foo}} instead of {{"Template shortcut|foo}}.

It's good to prepare template aliases which only differ in whitespaces and capitalization. For example, there's a template {{"See Wiktionary}}. The "W" is capital, since the word "Wiktionary" is so. But a redirect {{"See wiktionary}} with lower "w" exists because users are likely to use the latter.

Template limits[edit]

"Post-expand include size" limit. When templates are rendered or expanded to HTML for viewing in your browser, they use memory. This is called the "post-expand include size" and has a limit of 2,048,000 bytes. This size is included as an invisible comment in the HTML output—use your browser's view source feature to show the raw HTML and search for newpp. The report will look like:

<!--
NewPP limit report
Preprocessor node count: 2382/1000000
Post-expand include size: 63476/2048000 bytes
Template argument size: 9517/2048000 bytes
Expensive parser function count: 2/500
-->

The example shows that template expansion is using 63k out of 2M of available memory.

Display problem. If too many templates are included on a page, the post-expand include size may exceed the limit. When this happens, templates after the limit will no longer expand and will instead display as a wikilink (for example, Template:templatename). Common causes are the inclusion of too many citation templates and/or flag templates. To resolve this problem "substitute templates, remove templates, or split the page.


Non-rendered tranclusions still count towards limit. For example, a page which contains only {{#if:{{:Main Page}}}} would still have a post-expand include size even though it would have no output at all.

The same applies to "Scribunto modules. For example, {{#invoke:Test|main}} would still increase post-expand include size even if Module:Test were simply:

mw.getCurrentFrame():preprocess'{{msgnw::Main Page}}'-- remove this line and post-expand include size becomes zero
return {main = function()end}-- p.main() has no return value

Lua programming language[edit]

Since February 2013 "Lua programming language is available for use via the Scribunto MediaWiki extension. Lua code can be embedded into wiki templates by employing the "{{#invoke:}}" functionality of the Scribunto MediaWiki extension. The Lua "source code is stored in pages called modules, and these individual modules are then invoked on template pages. For example, "Module:Bananas can be invoked using the code {{#invoke:Bananas|hello}} to print the text "Hello, world!".

Template search[edit]

As an alternative to using this index linked above, you can search the Template namespace using the "Special:Search box below:

See also[edit]

Help pages Manual pages Special pages Other pages not for direct viewing

Notes[edit]

  1. ^ Namespaces from which transclusion is not allowed are specified on a wiki by the variable $wgNonincludableNamespaces
  2. ^ These are defined in the doBlockLevels function of Parser.php["dead link]
) ) WikipediaAudio is not affiliated with Wikipedia or the WikiMedia Foundation.