Difference between revisions of "Help:Parser functions"

From [N8]
Jump to navigation Jump to search
(Created page with "{{Construction}} '''Parser functions''' are very similar to variables but take one or more parameters (technically, any magic word tha...")
 
m (Fixed spelling)
 
Line 1: Line 1:
 
{{Construction}}
 
{{Construction}}
'''Parser functions''' are very similar to [[Help:Magic words#General_information|variables]] but take one or more parameters (technically, any magic word that takes a parameter is a parser function), and the name is sometimes prefixed with a [[wikipedia:Number sign|hash]] to distinguish them from templates. In addition to the parser functions included with MediaWiki the [[mw:Extensino:ParserFunctions|ParserFunctions extension]] installed here adds more.
+
'''Parser functions''' are very similar to [[Help:Magic words#General_information|variables]] but take one or more parameters (technically, any magic word that takes a parameter is a parser function), and the name is sometimes prefixed with a [[wikipedia:Number sign|hash]] to distinguish them from templates. In addition to the parser functions included with MediaWiki the [[mw:Extension:ParserFunctions|ParserFunctions extension]] installed here adds more.
  
 
Parser functions marked as "<span class="table-bg-orange ">[expensive]</span>" are tracked by the software, and the number that can be included on a page is limited (stacks with "<span class="table-bg-orange ">[expensive]</span>" [[Help:Magic words|magic words]]).
 
Parser functions marked as "<span class="table-bg-orange ">[expensive]</span>" are tracked by the software, and the number that can be included on a page is limited (stacks with "<span class="table-bg-orange ">[expensive]</span>" [[Help:Magic words|magic words]]).

Latest revision as of 22:09, 20 January 2021

N8.png
This page is currently under construction.
The information contained within should not be considered fully accurate and/or complete.

Parser functions are very similar to variables but take one or more parameters (technically, any magic word that takes a parameter is a parser function), and the name is sometimes prefixed with a hash to distinguish them from templates. In addition to the parser functions included with MediaWiki the ParserFunctions extension installed here adds more.

Parser functions marked as "[expensive]" are tracked by the software, and the number that can be included on a page is limited (stacks with "[expensive]" magic words).

Basic

Technical metadata of another page

Parser function Output
(for page Eris Ice)
Description
{{PAGEID: page name }} 24 [Expensive] Returns the page identifier of the specified page*.
{{PAGESIZE: page name}}
{{PAGESIZE: page name |R}}
0
452
[Expensive] Returns the byte size of the specified page. Use "|R" to get raw (unformatted) numbers.
{{PROTECTIONLEVEL:

action | page name}}

[Expensive] Outputs the protection level (e.g. "autoconfirmed", "sysop") for a given action (e.g. "edit", "move") on the specified page. Returns an empty string if not protected.
{{PROTECTIONEXPIRY:

action | page name}}

infinity [Expensive] Outputs the protection expiry (e.g. "20160418155030", "infinity") for a given action (e.g. "edit", "move") on the specified page. Returns "infinity" if not protected.
{{CASCADINGSOURCES: page name}} [Expensive] Returns the sources of any cascading protection acting on the specified page. Pages will not return their own title unless they transclude themselves.
{{REVISIONID: page name }} 5196 [Expensive] Unique revision ID of the last revision on the specified page*.
{{REVISIONDAY: page name }} 10 [Expensive] Day of edit from the last revision of the specified page* (unpadded number).
{{REVISIONDAY2: page name }} 10 [Expensive] Day of edit from the last revision of the specified page* (zero-padded number).
{{REVISIONMONTH: page name }} 06 [Expensive] Month of edit from the last revision of the specified page* (zero-padded number ).
{{REVISIONMONTH1: page name }} 6 [Expensive] Month of edit from the last revision of the specified page* (unpadded number).
{{REVISIONYEAR: page name }} 2020 [Expensive] Year of edit from the last revision of the specified page*.
{{REVISIONTIMESTAMP: page name }} 20200610205818 [Expensive] Timestamp as of time of edit on the specified page*.
{{REVISIONUSER: page name }} Oscillator [Expensive] The username from the last revision on the specified page*.
  • When the given param is equal to the current title of the parser, the parser function will yield the previous versions on preview and on substitution, that includes empty strings when used on page creation but using the values from the current version for page view, including viewing old revisions. In this case it is a non-expensive parser function.

URL data

Parser function Input → Output Description
{{localurl:page name}}
{{localurl:page name
|query_string}}
{{localurl:Cow}}
→ /Eris_Ice
{{localurl:Cow|printable=yes}}
→ /index.php?title=Eris_Ice&printable=yes
The relative path to the title.
{{fullurl:page name}}
{{fullurl:page name
|query_string}}

{{fullurl:interwiki:remote page name
|query_string}}
{{fullurl:Category:Non-player characters}}
https://wiki.geministation.com/Category:Non-player_characters

{{fullurl:Category:Non-player characters|action=edit}}
https://wiki.geministation.com/index.php?title=Category:Non-player_characters&action=edit
{{fullurl:ptrsw:Vaca|action=edit}}
https://wiki.geministation.com/index.php?title=Ptrsw:Vaca&action=edit
{{fullurl:ptrsw:Categoria:Monstros|action=edit}}
https://wiki.geministation.com/index.php?title=Ptrsw:Categoria:Monstros&action=edit

A protocol-relative path to the title, which depends on the $wgServer configuration setting for the local wiki (and so may or may not start with http(s)://). This will also resolve interwiki prefixes. Note: Unbracketed (plain) protocol-relative links are not automagically linked.
{{canonicalurl:page name}}
{{canonicalurl:page name
|query_string}}

{{canonicalurl:interwiki:remote page name
|query_string}}
{{canonicalurl:Category:Non-player characters}}
https://wiki.geministation.com/Category:Non-player_characters

{{canonicalurl:Category:Non-player characters|action=edit}}
https://wiki.geministation.com/index.php?title=Category:Non-player_characters&action=edit

The absolute path to the title, using the canonical URL. This will also resolve interwiki prefixes.
{{filepath:file name}}
{{filepath:file name|nowiki}}
{{filepath:file name|thumbnail_size'}}
{{filepath:Eris Ice.png}}
https://wiki.geministation.com/images/9/98/Eris_Ice.png

{{filepath:Eris Ice.png|nowiki}}
→ https://wiki.geministation.com/images/9/98/Eris_Ice.png
{{filepath:Eris Ice.png|300}}
https://wiki.geministation.com/images/9/98/Eris_Ice.png

The parameter nowiki usually removes the link around the filepath (which can't be seen in this example).

A protocol-relative path to the full size or thumbnail of a media file.
{{urlencode:string}} or
{{urlencode:string|QUERY}}
{{urlencode:string|WIKI}}
{{urlencode:string|PATH}}
{{urlencode:x:y/z á é}} or
{{urlencode:x:y/z á é|QUERY}}
→ x%3Ay%2Fz+%C3%A1+%C3%A9
{{urlencode:x:y/z á é|WIKI}}
→ x:y/z_%C3%A1_%C3%A9
{{urlencode:x:y/z á é|PATH}}
→ x%3Ay%2Fz%20%C3%A1%20%C3%A9

Note that the default is |QUERY.

The input encoded for use in URLs. Note that there is no urldecode function like there is in the obsolete StringFunctions extension.
Encoding
codespace
 none + 
QUERY + 
 WIKI _ 
 PATH%20
{{anchorencode:string}} {{anchorencode:x y z á é}}
→ x_y_z_.C3.A1_.C3.A9
The input encoded for use in URL section anchors (after the “#” symbol in a URL).

Namespaces

{{ns:}} returns the current localized name for the namespace with that index, canonical name, or local alias. Thus {{ns:6}}, {{ns:File}}, and {{ns:Image}} (an old name for the File namespace) all return "File". On a wiki where the content language is French, {{ns:Fichier}}</> is also valid, but >{{ns:Datei}} (the localisation of "File" in German) is not.

{{nse:}} is the equivalent encoded for MediaWiki URLs. It does the same, but it replaces spaces with underscores, making it usable in external links.

Standard namespaces:

Content namespaces Talk namespaces
Usage Output Usage Output
{{ns:-2}} / {{ns:Media}} Media {{ns:-1}} / {{ns:Special}} Special
(no talk page)
{{ns:0}} / {{ns:}} {{ns:1}} / {{ns:Talk}} Talk
{{ns:2}} / {{ns:User}} User {{ns:3}} / {{ns:User talk}} User talk
{{ns:4}} / {{ns:Project}} N8
Varies between wikis
{{ns:5}} / {{ns:Project talk}} N8 talk
{{ns:6}} / {{ns:File}} or {{ns:Image}} File {{ns:7}} / {{ns:File talk}} or {{ns:Image talk}} File talk
{{ns:8}} / {{ns:MediaWiki}} MediaWiki {{ns:9}} / {{ns:MediaWiki talk}} MediaWiki talk
{{ns:10}} / {{ns:Template}} Template {{ns:11}} / {{ns:Template talk}} Template talk
{{ns:12}} / {{ns:Help}} Help {{ns:13}} / {{ns:Help talk}} Help talk
{{ns:14}} / {{ns:Category}} Category {{ns:15}} / {{ns:Category talk}} Category talk

Don't confuse localised namespaces with custom namespaces.

Formatting

Usage Input → Output Description
{{formatnum:unformatted number}}

{{formatnum:formatnum-formatted number|R}}
{{formatnum:unformatted number|NOSEP}}

  • Simple:
    • {{formatnum:987654321.654321}}
      → 987,654,321.654321
    • {{formatnum:987,654,321.654321|R}}
      → 987654321.654321
  • Advanced:
    • {{formatnum:{{formatnum:987654321.654321}}|R}}
      → 987654321.654321 (on any locale)
    • {{formatnum:00001}}
      → 00,001
    • {{formatnum:987654321.654321 |NOSEP}}
      → 987654321.654321
    • Examples with বাংলা locale:
      • {{formatnum:987654321.654321}}
        → ৯৮,৭৬,৫৪,৩২১.৬৫৪৩২১
      • {{formatnum:987654321.654321 |NOSEP}}
        → ৯৮৭৬৫৪৩২১.৬৫৪৩২১
      • {{formatnum:৯৮,৭৬,৫৪,৩২১.৬৫৪৩২১ |R}}
        → 987654321.654321

Unsupported:
{{formatnum:{{formatnum:987.654.321}}}}
→ 987 654 321 (e.g. with Italian locale)


Examples of wrong input (unreliable output), with or without |R:
{{formatnum:987,654.321|R}} (the least broken)
{{formatnum:987.654,321|R}}
{{formatnum:987 654,321|R}}
{{formatnum:987&nbsp;654,321|R}}

Takes an unformatted number (Arabic, no group separators and . as decimal separator) and outputs it in the localized digit script and formatted with decimal and decimal group separators, according to the wiki's default locale.
The |R parameter can be used to reverse the behavior, for use in mathematical situations: it's reliable and should be used only to deformat numbers which are known to be formatted exactly as formatnum formats them with the wiki's locale.
The NOSEP ("no separators") parameter means that no group / decimal separators are changed; formatnum will only transform the digits themselves in languages which don't use the Hindu–Arabic numeral system. NOSEP can also prevent non-standard digit groupings you wouldn't expect.

Carter.png
Warning: Leading zeroes are not removed, you can use {{#expr:00001}} instead (from Extension:ParserFunctions).

Carter.png
Warning: If you don't input numbers in the exact format required, don't expect any reliable output, especially on non-English wikis.


If you really need to format (according the wiki's locale) a number in unknown input format, you could try and use formatnum two times (but not if it can have a decimal group, or its separator will be eaten or the number won't be formatted). Be aware that this is more a hack than a regular way to proceed, thus the output may be not reliable.

{{#dateformat:date}}
{{#formatdate:date}}
{{#dateformat:date|format}}
{{#formatdate:date|format}}

{{#dateformat:25 dec 2009|ymd}}
2009 December 25 (your pref), 2009 Dec 25 (default)
{{#formatdate:dec 25,2009|dmy}}
25 December 2009 (your pref), 25 Dec 2009 (default)
{{#dateformat:2009-12-25|mdy}}
December 25, 2009 (your pref), December 25, 2009 (default)
{{#formatdate:2009 dec 25|ISO 8601}}
2009-12-25 (your pref), 2009-12-25 (default)
{{#dateformat:25 decEmber|mdy}}
December 25 (your pref), DecEmber 25 (default)
Note: In the example hereinbefore, "your pref" refers to your date preference on the current MediaWiki wiki only.

Formats an unlinked date based on user "date format" preference, and adds metadata tagging it as a formatted date. For logged-out users and those who have not set a date format in their preferences, dates can be given a default: mdy, dmy, ymd, ISO 8601 (all case sensitive). If only the month and day are given, only mdy and dmy are valid. If a format is not specified or is invalid, the input format is used as a default. If the supplied date is not recognized as a valid date (specifically, if it contains any metadata such as from a nested use of these or similar templates), it is rendered unchanged, and no (additional) metadata is generated.
Carter.png
Warning: Although the ISO 8601 standard requires that dates be in the Gregorian calendar, the ISO parameter in this function will still format dates that fall outside the usual Gregorian range (e.g. dates prior to 1583). Also, the magic word cannot properly convert between negative years (used with ISO 8601) and years BC or years BCE (used in general writing).
{{lc:string}} {{lc:DATA CENTER}} → data center The lowercase input.
{{lcfirst:string}} {{lcfirst:DATA center}} → dATA center The input with the very first character lowercase.
{{uc:string}} {{uc:text transform}} → TEXT TRANSFORM The uppercase input.
{{ucfirst:string}} {{ucfirst:text tRAnSFORM}} → Text tRAnSFORM The input with the very first character uppercase.
{{padleft:xyz|stringlength}}

{{padleft:xyz|strlen|char}}
{{padleft:xyz|strlen|string}}

{{padleft:xyz|5}} → 00xyz

{{padleft:xyz|5|_}} → __xyz
{{padleft:xyz|5|abc}} → abxyz
{{padleft:xyz|2}} → xyz
{{padleft:|1|xyz}} → x (first character of the string)

Inserts a string of padding characters (character chosen in third parameter; default "0") of a specified length (second parameter) next to a chosen base character or variable (first parameter). The final digits or characters in the base replace the final characters in the padding; i.e. {{padleft:44|3|0}} produces 044. The padding string may be truncated if its length does not evenly divide the required number of characters.

All characters of the third parameter are used.

{{padright:xyz|stringlength}}
{{padright:xyz|strlen|char}}
{{padright:xyz|strlen|string}}
{{padright:xyz|5}} → xyz00

{{padright:xyz|5|_}} → xyz__
{{padright:xyz|5|abc}} → xyzab
{{padright:xyz|2}} → xyz
{{padright:|1|xyz}} → x

Identical to padleft but adds padding characters to the right side.

See also: Extension:StringFunctions (not installed).

Localization

Here are the magic words which are used as main localisation tools. Other magic words will often depend on the wiki's locale and configuration or on the chosen language: see in particular #Date and time, #Formatting, #Miscellaneous. More magic words can be added by the Extension:Translate.

Usage Input → Output Description
{{plural:2|is|are}} {{plural:0|is|are}} → are
{{plural:1*1|is|are}} → is
{{plural:21 mod 10|is|are}} → are
{{plural:{{#expr:21 mod 10}}|is|are}} → is
{{plural:1|is|are}} → is
{{plural:2|is|are}} → are
{{plural:-1|is|are}} → is
{{plural:-2|is|are}} → are
{{plural:0.5|is|are}} → are
{{plural:1.5|is|are}} → are
{{plural:-0.5|is|are}} → are
{{plural:-1.5|is|are}} → are
(For Russian)
{{PLURAL:5|1=Категория|Категории}}  → Категории


{{PLURAL:3|страница|страницы|страниц}} → страницы
{{PLURAL:5|страница|страницы|страниц}} → страниц

Outputs the singular form (second parameter) if the absolute value of the first parameter is an expression equalling one; the plural form (third parameter) otherwise. Its functioning is language-dependent.
{{grammar:N|noun}} Outputs the correct inflected form of the given word described by the inflection code after the colon (language-dependent). Grammar transformations are used for inflected languages like Polish. See also $wgGrammarForms.
{{gender:username|text for every gender}}

{{gender:Username|male text|female text|text for unspecified}}
{{gender:|male text|female text|text for unspecified}}
{{gender:.|male text|female text|text for unspecified}}

(Depends on the named user's gender) A switch for the gender set in Special:Preferences.

Note: The first example is basically a no-op
Note: If 3rd parameter is omitted and user hasn't defined their gender, then text if user is male is returned.
A blank username field ({{gender:|) means the current user, but can be used only in interface messages (MediaWiki namespace).
A dot username (.) means the default user gender on this wiki.

{{int:message name}} {{int:edit}}Edit
(Depends on user language; try: frja)
Internationalizes (translates) the given interface (MediaWiki namespace) message into the user language. For msgnw and other transclusion magic words, see the Transclusion modifiers section.
{{int:editsectionhint|MediaWiki}} {{int:editsectionhint|MediaWiki}}Edit section: MediaWiki You may also use parameters with translations.
Parameters are designated in messages with: $1, $2, $3, etc.
For example, here is the message for editsectionhint: Edit section: $1
In this example, MediaWiki replaces $1.

Transclusion modifiers

{{Page name|optional params}} usually transcludes another page, by default from the Template:namespace. These magic words modify that behavior.

Miscellaneous

ParserFunctions Extension

The Extenssion:ParserFunctions extension provides eleven additional parser functions to supplement the "magic words", which are already present in MediaWiki. All the parser functions provided by this extension take the form: {{#functionname: argument 1 | argument 2 | argument 3 ... }}

#expr

Type Operators
Grouping (parentheses) ( )
Numbers 1234.5   e (2.718)   pi (3.142)
binary operator e   unary +,-
Unary not ceil trunc floor abs exp ln sin cos tan acos asin atan
Binary ^
* / div mod
+ -
Round round
Logic = != <> > < >= <=
and
or

This function evaluates a mathematical expression and returns the calculated value. This function is also available in Extension:Scribunto via the mw.ext.ParserFunctions.expr function.

{{#expr: expression }}

The available operators are listed to the right, in order of precedence. See Help:Calculation for more details of the function of each operator. The accuracy and format of the result returned will vary depending on the operating system of the server running the wiki and the number format of the site language.

When evaluating using boolean algebra, zero evaluates to false, and any nonzero value, positive or negative, evaluates to true

{{#expr: 1 and -1 }}1
{{#expr: 1 and 0 }}0
{{#expr: 1 or -1 }}1
{{#expr: -1 or 0 }}1
{{#expr: 0 or 0 }}0

An empty input expression returns an empty string. Invalid expressions return one of several error messages, which can be caught using the #iferror function:

{{#expr: }}
{{#expr: 1+ }}Expression error: Missing operand for +.
{{#expr: 1 = }}Expression error: Missing operand for =.
{{#expr: 1 foo 2 }}Expression error: Unrecognized word "foo".

The order of addition and subtraction operands before or after a number is meaningful and may be treated as a positive or negative value instead of as an operand with an erroneous input:

{{#expr: +1 }}1
{{#expr: -1 }}-1
{{#expr: + 1 }}1
{{#expr: - 1 }}-1

Note, if using the output of magic words, you must raw-format them in order to remove commas and translate the numerals. For example, {{NUMBEROFUSERS}} results in 78, where we want 78, which can be obtained using {{formatnum:{{NUMBEROFUSERS}}|R}}. This is especially important in some languages, where numerals are translated. For example, in Bengali, {{NUMBEROFUSERS}} produces ৩০,০৬১.

{{#expr:{{NUMBEROFUSERS}}+100}} 178
{{#expr:{{formatnum:{{NUMBEROFUSERS}}|R}}+100}}178


Carter.png
Warning: The operator mod gives wrong results for some values of the second argument:
{{#expr: 123 mod (2^64-1)}}Division by zero. (produces an empty string; should be 123)

Note: If you want to do calculations based on dates (ex. test whether current date and time is after some other date and time), first convert the time to number of seconds after January 1, 1970 using {{#time: xNU }}, then you can simply add and subtract dates as numbers.

Rounding

Rounds off the number on the left to a multiple of 1/10 raised to a power, with the exponent equal to the truncated value of the number given on the right. To round up or down use unary ceil or floor respectively.

Test case Result Method of rounding
{{#expr: 1/3 round 5 }} 0.33333 Final digit is < 5, so no apparent rounding occurs
{{#expr: 1/6 round 5 }} 0.16667 Final digit is ≥ 5, so it is rounded up
{{#expr: 8.99999/9 round 5 }} 1 Again, the result is rounded up on the last digit, which results in additional rounding
{{#expr: 1234.5678 round -2 }} 1200 Rounded to nearest 100 because negative values round to the left of the decimal point
{{#expr: 1234.5678 round 2 }} 1234.57 Rounded to nearest 100th because positive values round to the right of the decimal point
{{#expr: 1234.5678 round 2.3 }} 1234.57 Decimals in the rounding index make no difference in the rounded result
{{#expr: trunc 1234.5678 }} 1234 <translate> Decimal portion truncated (chopped off)</translate>
Rounding to the nearest integer
{{#expr: 1/3 round 0 }} 0 Down to the nearest integer, which is zero
{{#expr: 1/2 round 0 }} 1 Up to the nearest integer, which is one
{{#expr: 3/4 round 0 }} 1 Up to the nearest integer, which is one
{{#expr: -1/3 round 0 }} -0 Up to the nearest integer, which is zero
{{#expr: -1/2 round 0 }} -1 Down to the nearest integer, which is negative one
{{#expr: -3/4 round 0 }} -1 Down to the nearest integer, which is negative one
colspan=3 Template:Hl2 | Rounding up or down with ceil and floor
{{#expr: ceil(1/3) }} 1 Up to the next larger integer, which is one
{{#expr: floor(1/3) }} 0 Down to the next smaller integer, which is zero
{{#expr: ceil(-1/3) }} -0 Up to the next larger integer, which is zero
{{#expr: floor(-1/3) }} -1 Down to the next smaller integer, which is negative one
{{#expr: ceil 1/3 }} 0.33333333333333 Not rounded, since 1 already is an integer
Carter.png
Warning: Interpreted as (ceil 1)/3, not ceil(1/3), as you might expect

Strings

Expressions only work with number-like values, they cannot compare strings or characters. #ifeq can be used instead.

{{#expr: "a" = "a" }}Expression error: Unrecognized punctuation character """.
{{#expr: a = a }}Expression error: Unrecognized word "a".
{{#ifeq: a | a | 1 | 0 }}1

#if

This function evaluates a test string and determines whether or not it is empty. A test string containing only white space is considered to be empty.

{{#if: test string | value if test string is not empty | value if test string is empty (or only white space) }}
{{#if:first parameter | second parameter | third parameter }}

This function first tests whether the first parameter is not empty. If the first parameter is not empty the function displays the second argument. If the first parameter is empty or contains only whitespace characters (spaces, newlines, etc.) it displays the third argument.

{{#if: | yes | no}}no
{{#if: string | yes | no}}yes
{{#if:      | yes | no}}no
{{#if:


| yes | no}}
no

The test string is always interpreted as pure text, so mathematical expressions are not evaluated:

{{#if: 1==2 | yes | no }}yes
{{#if: 0 | yes | no }}yes

The last parameter (false) may be omitted:

{{#if: foo | yes }} yes
{{#if: | yes }}
{{#if: foo | | no}}

The function may be nested. To do so, nest the inner #if function in its full form in place of a parameter of the enclosing #if function. Up to seven levels of nesting is possible, although that may depend on the wiki or a memory limit.

{{#if: test string | value if test string is not empty | {{#if: test string | value if test string is not empty | value if test string is empty (or only white space) >}} }}

You can also use a parameter as the test string in your #if statement. You need to ensure you add the | (pipe symbol) after the name of the variable. (So that if the parameter does not have a value, it evaluates to an empty string instead of the string "{{{1}}}".)

{{#if:{{{1|}}}|You entered text in variable 1|There is no text in variable 1 }}

See Help:Parser functions in templates for more examples of this parser function.

#ifeq

This parser function compares two input strings, determines whether they are identical, and returns one of two strings based on the result. If more comparisons and output strings are required, consider using #switch.

{{#ifeq: string 1 | string 2 | value if identical | value if different }}

If both strings are valid numerical values, the strings are compared numerically:

{{#ifeq: 01 | 1 | equal | not equal}}equal
{{#ifeq: 0 | -0 | equal | not equal}}equal
{{#ifeq: 1e3 | 1000 | equal | not equal}}equal
{{#ifeq: {{#expr:10^3}} | 1000 | equal | not equal}}equal

Otherwise the comparison is made as text; this comparison is case sensitive:

{{#ifeq: foo | bar | equal | not equal}}not equal
{{#ifeq: foo | Foo | equal | not equal}}not equal
{{#ifeq: "01" | "1" | equal | not equal}}not equal  

(compare to similar example above, without the quotes)

{{#ifeq: 10^3 | 1000 | equal | not equal}}not equal  (compare to similar example above, with #expr returning a valid number first)

As a practical example, consider an existing template Template:Timer using the parser to choose between two standard times, short and long. It takes the parameter as the first input to compare against the string "short" – there is no convention for the order, but it is simpler to read if the parameter goes first. The template code is defined as:

{{#ifeq: {{{1|}}} | short | 20 | 40 }}

the following ensue:

{{timer|short}}20
{{timer|20}}40
{{timer}}40
Carter.png
Warning: #ifexpr does not report equivalent numerical comparisons with the #ifeq and #switch parsers. These latter two are more accurate than #ifexpr, and do not return equivalent results.

Consider these comparison with the final digit changed:

{{#ifeq: 12345678901234567 | 12345678901234568 | equal | not equal}}not equal
{{#switch: 12345678901234567 | 12345678901234568 = equal | not equal}}not equal

Because PHP used in #ifeq and #switch compares two numbers of type integer, it returns the expected result correctly.

Whereas with #ifexpr and the same numbers:

{{#ifexpr: 12345678901234567 = 12345678901234568 | equal | not equal}}equal

With the different digit, the result of equal is actually incorrect.

This behaviour in #ifexpr is caused because MediaWiki converts literal numbers in expressions to type float, which, for large integers like these, involves rounding.

Carter.png
Warning: 1>ll|Strip marker</>|a unique code}}. This affects comparisons:
{{#ifeq: <nowiki>foo</nowiki> | <nowiki>foo</nowiki> | equal | not equal}}not equal
{{#ifeq: <math>foo</math> | <math>foo</math> | equal | not equal}}not equal
{{#ifeq: {{#tag:math|foo}} | {{#tag:math|foo}} | equal | not equal}}not equal
{{#ifeq: [[foo]] | [[foo]] | equal | not equal}}equal

If the strings to be compared are given as equal calls to the same template containing such tags, then the condition is true, but in the case of two templates with identical content containing such tags it is false.

Carter.png
Warning: Literal comparisons to page-name magic words may fail depending on site configuration.

For example, {{FULLPAGENAME}}, depending on wiki, may capitalize the first letter, and will replace all underscores with spaces.

To work around this, apply the magic word to both parameters:

{{#ifeq: {{FULLPAGENAME: L'Aquila}} | {{FULLPAGENAME}} | equal | not equal}}equal

#iferror

This function takes an input string and returns one of two results; the function evaluates to true if the input string contains an HTML object with class="error", as generated by other parser functions such as #expr, #time and #rel2abs, template errors such as loops and recursions, and other "failsoft" parser errors.

{{#iferror: test string | value if error | value if correct }}

One or both of the return strings can be omitted. If the correct string is omitted, the test string is returned if it is not erroneous. If the error string is also omitted, an empty string is returned on an error:

{{#iferror: {{#expr: 1 + 2 }} | error | correct }}correct
{{#iferror: {{#expr: 1 + X }} | error | correct }}error
{{#iferror: {{#expr: 1 + 2 }} | error }}3
{{#iferror: {{#expr: 1 + X }} | error }}error
{{#iferror: {{#expr: 1 + 2 }} }}3
{{#iferror: {{#expr: 1 + X }} }}
{{#iferror: {{#expr: . }} | error | correct }}correct
{{#iferror: <strong class="error">a</strong> | error | correct }}error

#ifexpr

This function evaluates a mathematical expression and returns one of two strings depending on the boolean value of the result:

{{#ifexpr: expression | value if true | value if false }}

The expression input is evaluated exactly as for #expr above, with the same operators being available. The output is then evaluated as a boolean expression. An empty input expression evaluates to false:

{{#ifexpr: | yes | no}}no

As mentioned above, zero evaluates to false and any nonzero value evaluates to true, so this function is equivalent to one using #ifeq and #expr only:

{{#ifeq: {{#expr: expression }} | 0 | value if false | value if true }}

except for an empty or wrong input expression (an error message is treated as an empty string; it is not equal to zero, so we get value if true).

{{#ifexpr: = | yes | no }} Expression error: Unexpected = operator.

comparing

{{#ifeq: {{#expr: = }} | 0 | no | yes }} yes

Either or both the return values may be omitted; no output is given when the appropriate branch is left empty:

{{#ifexpr: 1 > 0 | yes }}yes
{{#ifexpr: 1 < 0 | yes }}
{{#ifexpr: 0 = 0 | yes }} yes
{{#ifexpr: 1 > 0 | | no}}
{{#ifexpr: 1 < 0 | | no}} no
{{#ifexpr: 1 > 0 }}

#ifexist

This function takes an input string, interprets it as a page title, and returns one of two values depending on whether or not the page exists on the local wiki.

{{#ifexist: page title | value if exists | value if doesn't exist }}

The function evaluates to true if the page exists, whether it contains content, is visibly blank (contains meta-data such as category links or magic words, but no visible content), is blank, or is a redirect. Only pages that are redlinked evaluate to false, including if the page used to exist but has been deleted.

{{#ifexist: Help:Parser functions | exists | doesn't exist }}exists
{{#ifexist: XXHelp:Parser functionsXX | exists | doesn't exist }}doesn't exist

The function evaluates to true for system messages that have been customized, and for special pages that are defined by the software.

{{#ifexist: Special:Watchlist | exists | doesn't exist }}exists
{{#ifexist: Special:CheckUser | exists | doesn't exist }}exists (because the Checkuser extension is installed on this wiki)
{{#ifexist: MediaWiki:Copyright | exists | doesn't exist }}doesn't exist (because MediaWiki:Copyright has not been customized)

If a page checks a target using #ifexist:, then that page will appear in the Special:WhatLinksHere list for the target page. So if the code {{#ifexist:Foo }} were included live on this page (Help:Parser functions), Special:WhatLinksHere/Foo will list Help:Parser functions.

On wikis using a shared media repository, #ifexist: can be used to check if a file has been uploaded to the repository but not to the wiki itself:

{{#ifexist: File:Example.png | exists | doesn't exist }}doesn't exist
{{#ifexist: Image:Example.png | exists | doesn't exist }}doesn't exist
{{#ifexist: Media:Example.png | exists | doesn't exist }}doesn't exist

If a local description page has been created for the file, the result is exists for all of the above. #ifexist: does not work with interwiki links.

ifexist limits

#ifexist: is considered an "expensive parser function"; only a limited number of which can be included on any one page (including functions inside transcluded templates). When this limit is exceeded, any further #ifexist: functions automatically return false, whether the target page exists or not, and the page is categorized into Category:Pages with too many expensive parser function calls. The name of the tracking category may vary depending on the content language of your wiki.

For some use cases it is possible to emulate the ifexist effect with css, by using the selectors a.new (to select links to unexisting pages) or a:not(.new) (to select links to existing pages). Furthermore, since the number of expensive parser functions that can be used on a single page is controlled by {$wgExpensiveParserFunctionLimit, one can also increase the limit in LocalSettings.php if needed.

ifexist and wanted pages

A page that does not exist and is tested for using #ifexist will end up on the Wanted Pages.

#rel2abs

This function converts a relative file path into an absolute filepath.

{{#rel2abs: path }}
{{#rel2abs: path | base path }}

Within the path input, the following syntax is valid:

  • . → the current level
  • .. → go up one level
  • /foo → go down one level into the subdirectory /foo

If the base path is not specified, the full page name of the page will be used instead:

{{#rel2abs: /quok | Help:Foo/bar/baz }}Help:Foo/bar/baz/quok
{{#rel2abs: ./quok | Help:Foo/bar/baz }}Help:Foo/bar/baz/quok
{{#rel2abs: ../quok | Help:Foo/bar/baz }}Help:Foo/bar/quok
{{#rel2abs: ../. | Help:Foo/bar/baz }}Help:Foo/bar

Invalid syntax, such as /. or /./, is ignored. Since no more than two consecutive full stops are permitted, sequences such as these can be used to separate successive statements:

{{#rel2abs: ../quok/. | Help:Foo/bar/baz }}Help:Foo/bar/quok
{{#rel2abs: ../../quok | Help:Foo/bar/baz }}Help:Foo/quok
{{#rel2abs: ../../../quok | Help:Foo/bar/baz }}quok
{{#rel2abs: ../../../../quok | Help:Foo/bar/baz }}Error: Invalid depth in path: "Help:Foo/bar/baz/../../../../quok" (tried to access a node above the root node).

#switch

See also : Help:Switch parser function

This function compares one input value against several test cases, returning an associated string if a match is found.

{{#switch: ''comparison string''
 {{!}} ''case'' = ''result''
 {{!}} ''case'' = ''result''
 {{!}} ''...''
 {{!}} ''case'' = ''result''
 {{!}} ''default result''
}}

Examples:

{{#switch: baz | foo = Foo | baz = Baz | Bar }} Baz
{{#switch: foo | foo = Foo | baz = Baz | Bar }} Foo
{{#switch: zzz | foo = Foo | baz = Baz | Bar }} Bar

#switch with partial transclusion tags can affect a configuration file that enables an editor unfamiliar with template coding to view and edit configurable elements.

Default

The default result is returned if no case string matches the comparison string:

{{#switch: test | foo = Foo | baz = Baz | Bar }} Bar

In this syntax, the default result must be the last parameter and must not contain a raw equals sign (an equals sign without {{}}). If it does, it will be treated as a case comparison, and no text will display if no cases match. This is because the default value has not been defined (is empty). If a case matches however, its associated string will be returned.

{{#switch: test | Bar | foo = Foo | baz = Baz }} →
{{#switch: test | foo = Foo | baz = Baz | B=ar }} →
{{#switch: test | test = Foo | baz = Baz | B=ar }} → Foo

Alternatively, the default result may be explicitly declared with a case string of "#default".

{{#switch: ''comparison string''
 {{!}} ''case'' = ''result''
 {{!}} ''case'' = ''result''
 {{!}} ''...''
 {{!}} ''case'' = ''result''
 {{!}} #default = ''default result''
}}

Default results declared in this way may be placed anywhere within the function:

{{#switch: test | foo = Foo | #default = Bar | baz = Baz }} Bar

If the default parameter is omitted and no match is made, no result is returned:

{{#switch: test | foo = Foo | baz = Baz }}

Grouping results

It is possible to have 'fall through' values, where several case strings return the same result string. This minimizes duplication.

{{#switch: ''comparison string''
 {{!}} ''case1'' = ''result1''
 {{!}} ''case2'' 
 {{!}} ''case3'' 
 {{!}} ''case4'' = ''result234''
 {{!}} ''case5'' = ''result5''
 {{!}} ''case6'' 
 {{!}} ''case7'' = ''result67''
 {{!}} #default = ''default result''
}}

Here cases 2, 3 and 4 all return result234; cases 6 and 7 both return result67. The "#default = " in the last parameter may be omitted in the above case.

Use with parameters

The function may be used with parameters as the test string. In this case, it is not necessary to place the pipe after the parameter name, because it is very unlikely that you will choose to set a case to be the string "{{{parameter name}}}". This is the value the parameter will default to if the pipe is absent and the parameter doesn't exist or have a value. See Help:Parser functions in templates.

{{#switch: {{{1}}} | foo = Foo | baz = Baz | Bar }}

In the above case, if {{{1}}} equals foo, the function will return Foo. If it equals baz, the function will return Baz. If the parameter is empty or does not exist, the function will return Bar.

As in the section above, cases can be combined to give a single result.

{{#switch: {{{1}}} | foo | zoo | roo = Foo | baz = Baz | Bar }}

Here, if {{{1}}} equals foo, zoo or roo, the function will return Foo. If it equals baz, the function will return Baz. If the parameter is empty or does not exist, the function will return Bar.

Additionally, the default result can be omitted if you do not wish to return anything if the test parameter value does not match any of the cases.

{{#switch: {{{1}}} | foo = Foo | bar = Bar }}

In this case, the function returns an empty string unless {{{1}}} exists and equals foo or bar, in which case it returns Foo or Bar, respectively.

{{#switch: {{{1}}} | foo | zoo | roo = Foo | baz = Baz | }}

If for some reason you decide to set a case as "{{{parameter name}}}", the function will return that case's result when the parameter doesn't exist or doesn't have a value. The parameter would have to exist and have a value other than the string "{{{parameter name}}}" to return the function's default result.

(when {{{1}}} doesn't exist or is empty):
{{#switch: {{{1}}} | {{{1}}} = Foo | baz = Baz | Bar }} Foo
(when {{{1}}} has the value "test"):
{{#switch: {{{1}}} | {{{1}}} = Foo | baz = Baz | Bar }} Bar
(when {{{1}}} has the value "{{{1}}}"):
{{#switch: {{{1}}} | {{{1}}} = Foo | baz = Baz | Bar }} Foo

In this hypothetical case, you would need to add the pipe to the parameter ({{{1|}}}).

See also