Help:ParserFunctions

From: Everything Food & Drink.org
Jump to: navigation, search

The 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

Template:Hl1 | Type Template:Hl1 | 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.

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

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 foo 2 }}Expression error: Unrecognized word "foo".
This message box is using an invalid "type=warning" parameter and needs fixing.


#if

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

Either or both the return values may be omitted:

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

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

#ifeq

This parser function compares two strings and determines whether they are identical.

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

As a practical example, given an existing template Template:Size used to set standard short and long sizes, defined as:

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

the following ensue:

{{size|short}}20
{{size|20}}40
{{size}}40
This message box is using an invalid "type=warning" parameter and needs fixing.


This message box is using an invalid "type=warning" parameter and needs fixing.


#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: <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 ordinary string; it is not equal to zero, so we get value if true).

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:ParserFunctions | exists | doesn't exist }}exists
{{#ifexist: XXHelp:ParserFunctionsXX | exists | doesn't exist }}doesn't exist

The function evaluates to true for system messages that have been customised, 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 customised)

#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, the page is categorised into Category:Pages with too many expensive parser function calls, and any further #ifexist: functions automatically return false, whether the target page exists or not.

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:ParserFunctions), Special:WhatLinksHere/Foo will list Help:ParserFunctions.

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

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.

#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

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

Example:

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

#switch allows an editor to add information in one template and this information will be visible in several other templates which all have different formatting.

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.

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

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 = result2
 | case5 = result3
 | case6 
 | case7 = result4
 | #default = default result
}}

Here cases 2, 3 and 4 all return result2; cases 6 and 7 both return result4

Comparison behaviour

As with #ifeq, the comparison is made numerically if both the comparison string and the case string being tested are numeric; or as a case-sensitive string otherwise:

{{#switch: 0 + 1 | 1 = one | 2 = two | three}} → three
{{#switch: {{#expr: 0 + 1}} | 1 = one | 2 = two | three}} → one
{{#switch: a | a = A | b = B | C}} → A
{{#switch: A | a = A | b = B | C}} → C

A case string may be empty:

{{#switch: | = Nothing | foo = Foo | Something }}Nothing

Once a match is found, subsequent cases are ignored:

{{#switch: b | f = Foo | b = Bar | b = Baz | }}Bar
This message box is using an invalid "type=warning" parameter and needs fixing.


Raw equal signs

"Case" strings cannot contain raw equals signs. To work around this, create a template {{=}} containing a single equals sign: =.

Example:

{{#switch: 1=2
 | 1=2 = raw
 | 1<nowiki>=</nowiki>2 = nowiki
 | 1&#61;2 = html
 | 1{{=}}2 = template
 | default }}html

Note Note: For a simple real life example of the use of this function, check Template:NBA color. Two complex examples can be found at Template:Extension and Template:BOTREQ.

#time

Template:Hl1 | Code Template:Hl1 | Description Template:Hl1 | Current output
(Purge this page's cache to update)
Year
Y 4-digit year. 2017
y 2-digit year. 17
L 1 or 0 whether it's a leap year or not. 0
o ¹ ISO-8601 year number. ² 2017 ³

¹ Requires PHP 5.1.0 and newer and rev:45208.
² This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead.
³ Will output literal o if ¹ not fulfilled.

Month
n Month index, not zero-padded. 2
m Month index, zero-padded. 02
M An abbreviation of the month name, in the site language. Feb
F The full month name in the site language. February
xg Output the full month name in the genitive form for site languages that distinguish between genitive and nominative forms. For Polish:

(nominative)

{{#time:d F Y|20 June 2010}} → 20 czerwiec 2010

(genitive)

{{#time:d xg Y|20 June 2010}} → 20 czerwca 2010

Week
W ISO 8601 week number, zero-padded. 07
Day
j Day of the month, not zero-padded. 14
d Day of the month, zero-padded. 14
z Day of the year (January 1 = 0).
Note Note: To get the ISO day of the year add 1.
44
D An abbreviation for the day of the week. Rarely internationalised. Tue
l The full weekday name. Rarely internationalised. Tuesday
N ISO 8601 day of the week (Monday = 1, Sunday = 7). 2
w Number of the day of the week (Sunday = 0, Saturday = 6). 2
Hour
a "am" during the morning (00:00:00 → 11:59:59), "pm" otherwise (12:00:00 → 23:59:59). am
A Uppercase version of a above. AM
g Hour in 12-hour format, not zero-padded. 9
h Hour in 12-hour format, zero-padded. 09
G Hour in 24-hour format, not zero-padded. 9
H Hour in 24-hour format, zero-padded. 09
Minutes and seconds
i Minutes past the hour, zero-padded. 48
s Seconds past the minute, zero-padded. 18
U Seconds since January 1 1970 00:00:00 GMT. 1487065698
Miscellaneous
t Number of days in the current month. 28
c ISO 8601 formatted date, equivalent to Y-m-dTH:i:s+00:00. 2017-02-14T09:48:18+00:00
r RFC 5322 formatted date, equivalent to D, j M Y H:i:s +0000, with weekday name and month name not internationalised. Tue, 14 Feb 2017 09:48:18 +0000
Non-Gregorian calendars
Islamic
xmj Day of the month. 17
xmF Full month name. Jumada al-awwal
xmn Month index. 5
xmY Full year. 1438
Iranian
xij Day of the month. 26
xiF Full month name. Bahman
xin Month index. 11
xiY Full year. 1395
Hebrew
xjj Day of the month. 18
xjF Full month name. Shevat
xjt Number of days in month. 30
xjx Genitive form of the month name. Shevat
xjn Month number. 5
xjY Full year. 5777
Thai solar
xkY Full year. 2560
Minguo/Juche year
xoY Full year. 106
Japanese nengo
xtY Full year. 平成29
Flags
xn Format the next numeric code as a raw ASCII number. In the Hindi language, {{#time:H, xnH}} produces ०६, 06.
xN Like xn, but as a toggled flag, which endures until the end of the string or until the next appearance of xN in the string.
xr Format the next number as a roman numeral. Only works for numbers up to 3000. {{#time:xrY}} → MMXVII
xr Format the next number as a Hebrew numeral. {{#time:xhY}} → ב'י"ז

This parser function takes a date and/or time (in the Gregorian calendar) and formats it according to the syntax given. A date/time object can be specified; the default is the value of the magic word {{CURRENTTIMESTAMP}} – that is, the time the page was last rendered into HTML.

{{#time: format string }}
{{#time: format string | date/time object }}

The list of accepted formatting codes is given in the table to the right. Any character in the formatting string that is not recognised is passed through unaltered; this applies also to blank spaces (the system does not need them for interpreting the codes). There are also two ways to escape characters within the formatting string:

  1. A backslash followed by a formatting character is interpreted as a single literal character
  2. Characters enclosed in double quotes are considered literal characters, and the quotes are removed.

In addition, the digraph xx is interpreted as a single literal "x".

{{#time: Y-m-d }}2017-02-14
{{#time: [[Y]] m d }}2017 02 14
{{#time: [[Y (year)]] }}2017 (17UTCamTue, 14 Feb 2017 09:48:18 +0000)
{{#time: [[Y "(year)"]] }}2017 (year)
{{#time: i's" }}48'18"

The date/time object can be in any format accepted by PHP's strtotime() function. Both absolute (eg 20 December 2000) and relative (eg +20 hours) times are accepted.

{{#time: r|now}}Tue, 14 Feb 2017 09:48:18 +0000
{{#time: r|+2 hours}}Tue, 14 Feb 2017 11:48:18 +0000
{{#time: r|now + 2 hours}}Tue, 14 Feb 2017 11:48:18 +0000

If you've calculated a Unix timestamp, you may use it in date calculations by pre-pending an @ symbol.

{{#time: U | now }}1487065698
{{#time: r|@1487065698}}Tue, 14 Feb 2017 09:48:18 +0000

This message box is using an invalid "type=warning" parameter and needs fixing.


Full or partial absolute dates can be specified; the function will "fill in" parts of the date that are not specified using the current values:

{{#time: Y | January 1 }}2017
This message box is using an invalid "type=warning" parameter and needs fixing.


With MediaWiki r86805 - Code Review, a four-digit number is always interpreted as a year, never as hours and minutes:
{{#time: Y m d H:i:s | 1959 }}1959 02 14 00:00:00

A six-digit number is interpreted as hours, minutes and seconds if possible, but otherwise as an error (not, for instance, a year and month):
{{#time: Y m d H:i:s | 195909 }}2017 02 14 19:59:09 Input is treated as a time rather than a year+month code.
{{#time: Y m d H:i:s | 196009 }}Error: Invalid time. Although 19:60:09 is not a valid time, 196009 is not interpreted as September 1960.

The function performs a certain amount of date mathematics:

{{#time: d F Y | January 0 2008 }}31 December 2007
{{#time: d F | January 32 }}Error: Invalid time.
{{#time: d F | February 29 2008 }}29 February
{{#time: d F | February 29 2007 }}01 March
{{#time:Y-F|now -1 months}}2017-January


The total length of the format strings of the calls of #time is limited to 6000 characters [1].

#timel

This function is identical to {{#time: ... }}, except that it uses the local time of the wiki (as set in $wgLocaltimezone) when no date is given.

{{#time: Y-m-d }}2017-02-14
{{#timel: Y-m-d }}2017-02-14
{{#time: Y F d h:i:s}}2017 February 14 09:48:18
{{#timel: Y F d h:i:s}}2017 February 14 01:48:18

#titleparts

This function separates a pagetitle into segments based on slashes, then returns some of those segments as output.

{{#titleparts: pagename | number of segments to return | first segment to return }}

If the number of segments parameter is not specified, it defaults to "0", which returns all the segments. If the first segment parameter is not specified or is "0", it defaults to "1":

{{#titleparts: Talk:Foo/bar/baz/quok }}Talk:Foo/bar/baz/quok
{{#titleparts: Talk:Foo/bar/baz/quok | 1 }}Talk:Foo
{{#titleparts: Talk:Foo/bar/baz/quok | 2 }}Talk:Foo/bar
{{#titleparts: Talk:Foo/bar/baz/quok | 2 | 2 }}bar/baz

Negative values are accepted for both values. Negative values for number of segments effectively 'strips' segments from the end of the string. Negative values for first segment translates to "add this value to the total number of segments", loosely equivalent to "count from the right":

{{#titleparts: Talk:Foo/bar/baz/quok | -1 }}Talk:Foo/bar/baz Strips one segment from the end of the string
{{#titleparts: Talk:Foo/bar/baz/quok | -4 }}Strips all 4 segments from the end of the string
{{#titleparts: Talk:Foo/bar/baz/quok | -5 }}Strips 5 segments from the end of the string (more than exist)
{{#titleparts: Talk:Foo/bar/baz/quok | | -1 }}quok
{{#titleparts: Talk:Foo/bar/baz/quok | -1 | 2 }}bar/baz Strips one segment from the end of the string, then returns the second segment and beyond

The string is split a maximum of 25 times; further slashes are ignored and the 25th element will contain the rest of the string. The string is also limited to 255 characters, as it is treated as a page title:

{{#titleparts: a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/aa/bb/cc/dd/ee | 1 | 25 }}y/z/aa/bb/cc/dd/ee

If for whatever reason you needed to push this function to its limit, although very unlikely, it is possible to bypass the 25 split limit by nesting function calls:

{{#titleparts: {{#titleparts: a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/aa/bb/cc/dd/ee| 1 | 25 }} | 1 | 2}}z
This message box is using an invalid "type=warning" parameter and needs fixing.

You can use #titleparts as a small "string parser & converter", but consider that it returns the first substring capitalized. If lower case is needed, use lc: function to control output.

{{#titleparts: one/two/three/four|1|1 }}One
{{#titleparts: one/two/three/four|1|2 }}two
{{lc: {{#titleparts: one/two/three/four|1|1 }} }}one
This message box is using an invalid "type=warning" parameter and needs fixing.

This function does not degrade gracefully if your input exceeds 255 characters. If the inputted string is 256 characters long or more, this function will simply toss the string back at you.

General points

Substitution

Parser functions can be substituted by prefixing the hash character with subst::

{{subst:#ifexist: Help:ParserFunctions | [[Help:ParserFunctions]] | Help:ParserFunctions }} → the code [[Help:ParserFunctions]] will be inserted in the wikitext since the page Help:ParserFunctions exists.
This message box is using an invalid "type=warning" parameter and needs fixing.


Tables

Parser functions will mangle wikitable syntax, treating all the raw pipe characters as parameter divisors. To avoid this, most wikis create the template Template:! with its contents only a raw pipe character (|). This 'hides' the pipe from the MediaWiki parser, ensuring that it is not considered until after all the templates and variables on a page have been expanded. Alternatively, raw HTML table syntax can be used, although this is less intuitive and more error-prone.

Stripping whitespace

Whitespace, including newlines, tabs, and spaces, is stripped from the beginning and end of all the parameters of these parser functions. If this is not desirable, comparison of strings can be done after putting them in quotation marks.

{{#ifeq: foo            |            foo | equal | not equal }}
equal
{{#ifeq: "foo           " | "           foo" | equal | not equal }}
not equal

For preventing trimming then- and else-parts, see m:Template:If.

See also

Language: English