Help:ParserFunctions: Difference between revisions

From innovaphone wiki
Jump to navigation Jump to search
m (1 revision(s))
 
(test)
Line 1: Line 1:
#redirect [[ParserFunctions]]{{R from alternative name}}
{{extension
|name = ParserFunctionsFunction
|image =
|type = Parser Extension
|maturity = Beta/Stable
|mediawiki = > 1.6.8
|version = N/A
|update = 2006-11-21
|description = A collection of parsefunctions such as branching instructions and expression handler and time calculation unit.
}}
 
 
MediaWiki extension '''ParserFunctions''' is a collection of [[Help:parser function|parser functions]] (note the difference between the name of the collection, and the general term). These parser functions have a hash character in front of the function name, so they typically have the syntax:
:{{ft|#functionname|<nowiki>argument 1 | argument 2 | argument 3...</nowiki>}}
 
With [[Special:ExpandTemplates]] one can evaluate expressions with parser functions directly.
 
== Functions ==
This module defines eight functions at present:
<tt>[[#.23expr:|expr]]</tt>,
<tt>[[#.23if:|if]]</tt>,
<tt>[[#.23ifeq:|ifeq]]</tt>,
<tt>[[#.23ifexist:|ifexist]]</tt>,
<tt>[[#.23ifexpr:|ifexpr]]</tt>,
<tt>[[#.23switch:|switch]]</tt>,
<tt>[[#.23time:|time]]</tt>, and
<tt>[[#.23rel2abs:|rel2abs]]</tt>.
<br><br>
<h3 style="background: beige">#expr:</h3>
 
:''The accuracy and format of numeric results varies with the operating system of the server.''
 
The <tt>expr</tt> function computes mathematical expressions based on permutations of numbers (or [[variable]]s/[[parameter]]s that translate to numbers) and operators.  It does ''not'' work with strings; use <tt>ifeq</tt> below instead.  The syntax is:
 
{{ft|#expr|expression}}
 
A list of supported operators follows.  For more details about the operator precedence see [[Help:Calculation]],
it's roughly '''(1)''' grouping (parentheses), '''(2)''' unary (+/- signs and NOT), '''(3)''' multiplicative (*, /, div, mod), '''(4)''' additive (+ and -), '''(5)''' round, '''(6)''' comparative (=, !=, &lt;, &gt;, etc.), '''(7)''' logical AND, '''(8)''' logical OR.
Within the same precedence class operators are evaluated left to right. As always some redundant parentheses are better than erroneous terse code.
 
{| class="wikitable"
! ''Operator''
! ''Operation''
! ''Example''
|-
|rowspan="2" colspan="2" align="center"| none
|
{{ft|#expr|123456789012345}} = {{#expr: 123456789012345}}
|-
|
{{ft|#expr|0.000001}} = {{#expr: 0.000001}}
|-
! ( )
| Grouping operators
|
{{ft|#expr|(30 + 7) * 7 }} = {{#expr: (30 + 7) * 7 }}
|-
! +
| Unary '''<tt>+</tt>''' sign
|
{{ft|#expr|+30 * +7}} = {{#expr: +30 * +7}}
|-
! -
| Unary '''<tt>-</tt>''' sign (negation)
|
{{ft|#expr|-30 * -7}} = {{#expr: -30 * -7}}
|-
! not
|  Unary NOT, logical NOT
|
{{ft|#expr|not 0 * 7}} = {{#expr: not 0 * 7}}<br />
{{ft|#expr|not 30 + 7}} = {{#expr: not 30+7}}
|-
! *
| Multiplication
|
{{ft|#expr|30 * 7}} = {{#expr: 30 * 7}}
|-
! /
| Division, same as '''div'''
|
{{ft|#expr|30 / 7}} = {{#expr: 30 / 7}}
|-
! div
| Division, same as '''/''',<br />no integer division
|
{{ft|#expr|30 div 7}} = {{#expr: 30 div 7}}<br />
{{ft|#expr|5 div 2 * 2 + 5 mod 2}} = {{#expr: 5 div 2 * 2 + 5 mod 2}}
|-
! mod
| "Modulo", remainder of division after truncating both operands to an integer.<br />Caveat, '''div''' and '''mod''' are different from all programming languages.
|
{{ft|#expr|30 mod 7}} = {{#expr: 30 mod 7}}<br />
{{ft|#expr|-8 mod -3}} = {{#expr: -8 mod -3}}<br />
{{ft|#expr|-8 mod +3}} = {{#expr: -8 mod +3}}<br />
{{ft|#expr|8 mod 2.7}} = {{#expr: 8 mod 2.7}}<br />
{{ft|#expr|8 mod 3.2}} = {{#expr: 8 mod 3.2}}<br />
{{ft|#expr|8.9 mod 3}} = {{#expr: 8.9 mod 3}}
|-
! <tt>+</tt>
| Addition
|
{{ft|#expr|30 + 7}} = {{#expr: 30 + 7}}
|-
! <tt>-</tt>
| Subtraction
|
{{ft|#expr|30 - 7}} = {{#expr: 30 - 7}}
|-
! round
| Rounds off the number on the left to the power of 1/10 given on the right
|
{{ft|#expr|30 / 7 round 3}} = {{#expr: 30 / 7 round 3}}<br />
{{ft|#expr|30 / 7 round 0}} = {{#expr: 30 / 7 round 0}}<br />
{{ft|#expr|3456 round -2}} = {{#expr: 3456 round -2}}
|-
! =
| Equality (numerical incl. logical)
|
{{ft|#expr|<nowiki>30 = 7</nowiki>}} = {{#expr: 30 = 7}}
|-
! &lt;&gt;
| Inequality, same as '''!='''
|
{{ft|#expr|30 &lt;&gt; 7}} = {{#expr: 30 <> 7}}
|-
! !=
| Inequality, same as '''&lt;&gt;''', logical ''xor''
|
{{ft|#expr|<nowiki>1 != 0</nowiki>}} = {{#expr: 1 != 0}}
|-
! &lt;
| Less than
|
{{ft|#expr|30 &lt; 7}} = {{#expr: 30 < 7}}
|-
! &gt;
| Greater than
|
{{ft|#expr|30 &gt; 7}} = {{#expr: 30 > 7}}
|-
! &lt;=
| Less than or equal to
|
{{ft|#expr|<nowiki>30 &lt;= 7</nowiki>}} = {{#expr: 30 <= 7}}
|-
! &gt;=
| Greater than or equal to
|
{{ft|#expr|<nowiki>30 &gt;= 7</nowiki>}} = {{#expr: 30 >= 7}}
|-
! and
| Logical AND
|
{{ft|#expr|4 &lt; 5 and 4 mod 2}} = {{#expr: 4<5 and 4 mod 2}}
|-
! or
| Logical OR
|
{{ft|#expr|4 &lt; 5 or 4 mod 2}} = {{#expr: 4<5 or 4 mod 2}}
|}
 
The boolean operators consider '''0''' to be "false" and any other number to be "true", on output "true" is shown as '''{{#expr: 30 and 7}}'''.
 
Numbers are given in decimal with "." for the decimal point. The <code>[[Help:Magic words#Formatting|formatnum:]]</code> function can be used to change the decimal point to a comma for the appropriate locales. Scientific notation with <tt>E</tt> plus exponent is not yet supported on input for expressions, but used on output, for details see [[Help:Calculation]].
 
<h3 style="background: beige">#if:</h3>
 
The {{ft|#if}} function is an if-then-else construct. The syntax is:
 
{{ft|#if|&lt;condition string&gt; &#124; &lt;then text&gt; &#124; &lt;else text&gt;}}
{{ft|#if|&lt;condition string&gt; &#124; &lt;then text&gt;}}
 
The applied condition is "The condition string is non-empty". Thus, if the condition string is empty or consists only of whitespace, then the condition is false, and the ''else text'' is returned. Otherwise, the ''then text'' is returned. The ''else text'' may be omitted, in which case the result will be blank if the condition is false.
 
An example:
{{ft|#if| <nowiki>{{{parameter|}}} | Parameter is defined. | Parameter is undefined, or empty</nowiki> }}
 
Note that the condition string is not itself a condition such as "1 = 2"; for example,  {{ft|#if|<nowiki>1 = 2 | yes | no</nowiki>}} will return "yes", because the string "<code>1 = 2</code>" is not blank. Thus the {{ft|#if}} function does '''not''' support "=" signs or mathematical expressions.
 
<h3 style="background: beige">#ifeq:</h3>
 
{{ft|#ifeq}} compares two strings or numbers, and returns another string depending on the result of that comparison. The syntax is:
 
{{ft|#ifeq|&lt;text 1&gt; &#124; &lt;text 2&gt; &#124; &lt;equal text&gt; &#124; &lt;not equal text&gt; }}
 
If both strings can be interpreted as numbers the comparison is numerical. To force a string comparison add tokens that can't be interpreted as numbers:
 
:{{ft|#ifeq|<nowiki>+07 | 007 | 1 | 0</nowiki>}} gives {{#ifeq: +07 | 007 | 1 | 0 }}
:{{ft|#ifeq|<nowiki>"+07" | "007" | 1 | 0</nowiki>}} gives {{#ifeq:"+07"|"007"| 1 | 0 }}
 
Comparison of strings is case-sensitive:
:{{ft|#ifeq|<nowiki>A | a | 1 | 0</nowiki>}} gives {{#ifeq: A | a | 1 | 0 }}
 
;For compatibility with older templates [[#.23if:|#if:]] cannot directly distinguish defined and undefined parameter values, it's a shorthand for a comparison with the empty string. With [[#.23ifeq:|#ifeq:]] it's directly possible to identify undefined parameters&#58;
:{{ft|#if|<nowiki>{{{x| }}} | not blank | blank</nowiki>}} = {{#if: {{{x|}}}|not blank|blank}},
:{{ft|#ifeq|<nowiki>{{{x| }}} | | blank | not blank</nowiki>}} = {{#ifeq: {{{x|}}}| |blank|not blank}},
:{{ft|#ifeq|<nowiki>{{{x| }}} | {{{x|u}}} | defined | undefined</nowiki>}} = {{#ifeq: {{{x|}}}|{{{x|u}}}|defined|undefined}}.
;An undefined parameter without default counts in the comparison as a string consisting of the tag&#58;
:{{ft|#ifeq|<nowiki>{{{x}}} | </nowiki>{{tlp|concat|<nowiki>{|{|{x}|}|}</nowiki>}}<nowiki> | 1 | 0</nowiki>}} = {{ #ifeq: {{{x}}}|{{ concat|{|{|{x}|}|} }}|1|0}}.
 
<h3 style="background: beige">#ifexist:</h3>
 
{{ft|#ifexist}} returns one of two results based on whether or not a named title exists.
 
{{ft|#ifexist|<nowiki>&lt;article&gt; | &lt;if article exists&gt; | &lt;if article exists not&gt; </nowiki>}}
 
 
The usual case-sensitivity applies: if a page exists then also a non-canonical name for that page gives a positive result. E.g. on Meta:
:{{ft|#ifexist|<nowiki>Bugs|Foo|RFC 3092</nowiki>}} gives {{#ifexist:Bugs|Foo|RFC 3092}}, because [[Bugs]] exists
:{{ft|#ifexist|<nowiki>bugs|Foo|RFC 3092</nowiki>}} gives {{#ifexist:bugs|Foo|RFC 3092}}, because [[bugs]] is in canonical form the existing [[Bugs]]
:{{ft|#ifexist|<nowiki>BUGS|Foo|RFC 3092</nowiki>}} gives {{#ifexist:BUGS|Foo|RFC 3092}} because [[BUGS]] does not exist
:{{ft|#ifexist|<nowiki>m:Help:Calculation|Yes|Oops</nowiki>}} gives {{#ifexist:m:Help:Calculation|Yes|Oops}} although [[m:Help:Calculation]] exists, because of the interwiki prefix.
 
The first parameter is the title to check for, the second is the positive result, and the third, the negative result. If the parameter passed does not produce a valid title object, then the result is negative.
 
{{tim|exists}} gives the same result, except that the result is positive for an interwiki link. You can also handle an interwiki link differently with {{tim|if interwiki link}}.
 
{{ft|#ifexist}} doesn't handle relative paths (like '../foo'), for that, use it in combination of {{ft|#rel2abs}}.
 
<h3 style="background: beige">#ifexpr:</h3>
{{ft|#ifexpr}} evaluates a mathematical expression and returns one of two strings depending on the result.
 
{{ft|#ifexpr|<nowiki>&lt;expression&gt; | &lt;then text&gt; | &lt;else text&gt; </nowiki>}}
 
 
If the expression evaluates to zero, then the ''else text'' is returned, otherwise the ''then text'' is returned. Expression syntax is the same as for <tt>expr</tt>.
 
;At the moment the ''else text'' is also returned for an empty expression&#58;
:{{ft|#ifexpr|<nowiki>{{ns:0}}|Toast| '''or else'''</nowiki>}} gives {{#ifexpr: {{ns:0}}|Toast|'''or else'''}}
;Omitting both ''then text'' and ''else text'' gives no output except possibly an error message; this can be used to check the correctness of an expression, or to check the wording of the error message (emulated ''assertions'', forced errors)&#58;
:{{ft|#ifexpr|1/{{ft sub|#ifeq|{{ft sub|ns|4}} <nowiki>| Meta | 1 | 0</nowiki>}}}} {{#ifexpr: 1/{{#ifeq: {{ns:4}}|Meta|1|0}}}} -- no result, hence "<nowiki>1/{{#ifeq: {{ns:4}}|Meta|1|0}}"</nowiki> is a correct expression
:{{ft|#ifexpr|1/{{ft sub|#ifeq|{{ft sub|ns|0}} <nowiki>| Meta | 1 | 0</nowiki>}}}} {{#ifexpr: 1/{{#ifeq: {{ns:0}}|Meta|1|0}}}}
:{{ft|#if|{{ft sub|#ifexpr|<nowiki>1=2</nowiki>}}<nowiki> | wrong | correct</nowiki>}} {{#if:{{#ifexpr: 1=2}}|wrong|correct}} -- "1=2" is a correct Boolean expression (not to be confused with one with the value 1, representing "true")
:{{ft|#if|{{ft sub|#ifexpr|1E2}}<nowiki> | wrong | correct</nowiki>}} {{#if:{{#ifexpr: 1E2}}|wrong|correct}} -- "1E2" not allowed in expressions
:{{ft|#if|{{ft sub|#ifexpr|1/0}}<nowiki> | wrong | correct</nowiki>}} {{#if:{{#ifexpr: 1/0}}|wrong|correct}} -- "1/0" not allowed
 
:{{ft|#if|{{ft sub|#ifexpr|<nowiki>a=b</nowiki>}}<nowiki> | wrong | correct</nowiki>}} {{#if:{{#ifexpr: a=b}}|wrong|correct}} ("a=b" not allowed, to compare strings use #ifeq)
 
Example of an application: <nowiki>{{ #if: {{#ifexpr: {{PAGENAME}} }} || </nowiki>''action if PAGENAME is a number (or correct numeric expression)'' }}
 
For another application, see also {{tim|evalns}}.
 
<h3 style="background: beige">#switch:</h3>
 
<code>switch</code> compares a single value against multiple others, returning a string if a match is found. The syntax is basically:
 
{{ft begin|#switch}} <span style="color: green;">''&lt;comparison value&gt;''</span>
  | ''&lt;value<sub>1</sub>&gt;'' = ''&lt;result<sub>1</sub>&gt;''
  | ''&lt;value<sub>2</sub>&gt;'' = ''&lt;result<sub>2</sub>&gt;''
  | ''...''
  | ''&lt;value<sub>n</sub>&gt;'' = ''&lt;result<sub>n</sub>&gt;''
  | <span style="color: blue;">''&lt;default result&gt;''</span>
{{ft_end}}
 
<code>switch</code> will search through each value passed until a match is found with the comparison value. When found, the result for that value is returned (the text string after the equal sign). If no match is found, but the last item has no equal sign in it, it will be returned as the default result. If your default result ''must'' have an equal sign, you may use <code>#default</code>:
 
{{ft begin|#switch}} <span style="color: green;">''&lt;comparison value&gt;''</span>
  | ''&lt;value&gt;'' = ''&lt;result&gt;''
  | <span style="color: blue;">#default = ''&lt;default result&gt;''</span>
{{ft end}}
 
Note that it's also possible to have "fall through" for values (reducing the need to duplicate results). For example:
 
{{ft begin|#switch}} <span style="color: green;">''&lt;comparison value&gt;''</span>
| ''&lt;value<sub>1</sub>&gt;''
| ''&lt;value<sub>2</sub>&gt;''
| ''&lt;value<sub>3</sub>&gt;'' = ''&lt;result<sub>3</sub>&gt;''
| ''...''
| ''&lt;value<sub>n</sub>&gt;'' = ''&lt;result<sub>n</sub>&gt;''
| <span style="color: blue;">''&lt;default result&gt;''</span>
{{ft end}}
 
Note how value<sub>1</sub> and value<sub>2</sub> contain no equal sign. If they're matched, they are given the result for value<sub>3</sub> (that is, whatever is in result<sub>3</sub>).
 
;As for [[##ifeq:|#ifeq:]] the comparison is numerical where possible&#58;
:{{ft|#switch|<nowiki>+07 | 7 = Yes | 007 = Bond | No </nowiki>}} gives {{ #switch: +07 | 7 = Yes | 007 = Bond | No }}
:{{ft|#switch|<nowiki>"+07"|"7"= Yes |"007"= Bond | No </nowiki>}} gives {{ #switch:"+07"|"7"= Yes |"007"= Bond | No }}
;The matched value can be empty, therefore the following constructs are equivalent&#58;
:{{ft|#if|<nowiki>{&#123;ns:0&#125;} | not empty | empty </nowiki>}} gives {{ #if: {{ns:0}} | not empty | empty }}
:{{ft|#switch|<nowiki>{&#123;ns:0&#125;}|=empty|not empty </nowiki>}} gives {{ #switch:{{ns:0}}|=empty|not empty }}
 
Comparison of strings is case-sensitive:
:{{ft|#switch|<nowiki>A | a=lower | A=UPPER </nowiki>}} gives {{#switch: A | a=lower | A=UPPER }}
:{{ft|#switch|<nowiki>A | a=lower | UPPER </nowiki>}} gives {{#switch: A | a=lower | UPPER }}
:{{ft|#switch|<nowiki>a | a=lower | UPPER </nowiki>}} gives {{#switch: a | a=lower | UPPER }}
 
This is not to be confused with the fact that parser function names are case-insensitive:
:{{ft|#swItch|<nowiki>A | a=lower | UPPER </nowiki>}} gives {{#swItch: A | a=lower | UPPER }}
 
To have the [[##switch:|#switch]] statement be case-insensitive, use the construct <nowiki>{{lc:}}</nowiki> or <nowiki>{{uc:}}</nowiki>
:{{ft|#switch|<nowiki>{{lc:A}} | a=lower | A=UPPER </nowiki>}} gives {{#switch: {{lc:A}} | a=lower | A=UPPER }}
:{{ft|#switch|<nowiki>{{lc:A}} | a=lower | UPPER </nowiki>}} gives {{#switch: {{lc:A}} | a=lower | UPPER }}
:{{ft|#switch|<nowiki>{{lc:a}} | a=lower | UPPER </nowiki>}} gives {{#switch: {{lc:a}} | a=lower | UPPER }}
 
This is usually used in templates, when you want to have case-insensitivity on in param values:
{{ft begin|#switch}} <span style="color: green;">{{ft sub|lc|<nowiki>{{{1| B }}}</nowiki>}}</span>
| a
| b
| c = <nowiki>'''''abc''' or '''ABC'''''</nowiki>
| A
| B
| C = <nowiki>''Memory corruption due to cosmic rays''</nowiki>
| <span style="color: blue;">#default = ''N/A''</span>
{{ft end}}
gives {{#switch: {{lc: {{{1| B }}} }}
| a
| b
| c = '''''abc''' or '''ABC'''''
| A
| B
| C = ''Memory corruption due to cosmic rays''
| #default = N/A
}}
 
[[##switch:|#switch]] may be used instead of [[##ifeq:|#ifeq]]:
:{{ft|#switch|<nowiki>a | a=true | false </nowiki>}} gives {{#switch: a | a=true | false }}
:{{ft|#ifeq|<nowiki>a | a | true | false </nowiki>}} gives {{#ifeq: a | a | true | false }}
 
<h3 style="background: beige">#time:</h3>
 
{{ft|#time}} is a time and date formatting function. The syntax is:
 
{{ft|#time|format}}
{{ft|#time|format &#124; time}}
 
If the time is not specified, the time at which the article is converted to HTML is used. Note that due to caching, this may be up to a week different to the time at which the article is viewed. Manual updates may be required, this can be achieved by saving the page without making any changes (a "null edit") or viewed with <code>action=purge</code> in search string of URL or viewed by a user whose option is "Disable page caching".
 
The ''format'' parameter is a format string similar to the one used by [http://www.php.net/date PHP's date].
 
The following format codes have the same meaning as in PHP. Significant differences from PHP's behaviour, apart from internationalisation (i.e. language and locale differences), should be considered an error of ParserFunctions and should be reported. All numeric format codes return numbers formatted according to the local language, use the xn code described below to override this.
 
{| cellpadding="6px" border=1 style="border:1px solid #C0C0C0; border-collapse:collapse;"
! Code
! Description
! Example output
! Current output
|-
|colspan="4"| Year:
|-
| Y
| The 4-digit year.
| e.g. 2006
| {{#time:Y}}
|-
| y
| The 2-digit year.
| 00 to 99, e.g. 06 for year 2006.
| {{#time:y}}
|-
|colspan="4"| Month:
|-
| n
| The month number, not zero-padded.
| 1 to 12
| {{#time:n}}
|-
| m
| The month number, zero-padded.
| 01 to 12
| {{#time:m}}
|-
| M
| An abbreviation of the month name. Often internationalised.
| Jan to Dec
| {{#time:M}}
|-
| F
| The full month name. Often internationalised.
| January
| {{#time:F}}
|-
|colspan="4"| Week:
|-
| W
| ISO 8601 week number (ISO years have full weeks from monday to sunday, and ISO week number 1 always contains January 4 or the first thursday of the civil year), zero-padded.
| 01 to 52 or 53 (depends on year)
| {{#time:W}}
|-
|colspan="4"| Day:
|-
| j
| The day of the month, not zero-padded.
| 1 to 31
| {{#time:j}}
|-
| d
| The day of the month, zero-padded.
| 01 to 31
| {{#time:d}}
|-
| z
| The day of the year (starting from 0)
| 0 to 364, or 365 on a leap year
| {{#time:z}}
|-
| D
| An abbreviation for the day of the week. Rarely internationalised.
| Mon to Sun
| {{#time:D}}
|-
| l
| The full weekday name. Rarely internationalised.
| Monday to Sunday
| {{#time:l}}
|-
| N
| ISO 8601 day of the week (according to the ISO 8601 week).
| 1 (for Monday) through 7 (for Sunday)
| {{#time:N}}
|-
| w
| number of the day of the week (according to the American week).
| 0 (for Sunday) through 6 (for Saturday)
| {{#time:w}}
|-
|colspan="4"| Hour:
|-
| a
| am (between 01:00:00 and 12:59:59 on the same day) or pm, with lowercase (used with the 12-hour format).
| am or pm
| {{#time:a}}
|-
| A
| Same as with code <tt>a</tt> above, but with uppercase.
| AM or PM
| {{#time:A}}
|-
| g
| 12-hour format of the hour without leading zeros (one or two digits, used with am/pm or AM/PM).
| 1 to 12
| {{#time:g}}
|-
| h
| 12-hour format of the hour, with leading padding zero (two digits, used with am/pm or AM/PM).
| 01 to 12
| {{#time:h}}
|-
| G
| 24-hour format of the hour, without leading padding zero (one or two digits).
| 0 to 23
| {{#time:G}}
|-
| H
| 24-hour format of the hour, with leading padding zero (two digits).
| 00 to 23
| {{#time:H}}
|-
|colspan="4"| Minutes and seconds:
|-
| i
| The minute, with leading padding zero (two digits).
| 00 to 59
| {{#time:i}}
|-
| s
| The second, with leading padding zero (two digits).
| 00 to 59
| {{#time:s}}
|-
| U
| Seconds since January 1 1970 00:00:00 GMT.
| 0 to infinite
| {{#time:U}}
|-
|colspan="4"| Miscellaneous:
|-
| L
| Whether it's a leap year.
| 1 if it is a leap year, 0 otherwise.
| {{#time:L}}
|-
| t
| Number of days in the month.
| 28 to 31
| {{#time:t}}
|-
| c
| ISO 8601 formatted date, same as {&#123;#time:Y-m-dTH:i:s{&#123;#time:+H:i&#124;+0 hours&#125;}&#125;}.
| fixed length string
| {{#time:c}}
|-
| r
| RFC 2822 formatted date, same as {&#123;#time:D, j M Y H:i:s {&#123;#time:+H:i&#124;+0 hours&#125;}&#125;}.
| variable length string
| {{#time:r}}
|}
 
The following format codes are extensions to the PHP syntax:
 
{| cellpadding="6px" border=1 style="border:1px solid #C0C0C0; border-collapse:collapse;"
! Code
! Description
|--------------
| xn
| Format the next numeric code as a raw ASCII number. For example, in the Hindi language, {{ft|#time|H, xnH}} produces ०६, 06.
|--------------
| xN
| Toggle a permanent raw number formatting flag. Like xn, except it lasts until the end of the string or until the same code appears again.
|--------------
| xr
| Format the next numeric code as a roman numeral. Only works for numbers up to 3000.
|--------------
| xg
| Output the genitive form of the month name, for languages which make such a distinction between genitive and nominative.
|--------------
| xx
| A literal "x"
|}
 
Any unrecognised character will be passed through to the output unmodified. There are also two quoting conventions which can be used to output literal characters.
 
* Characters enclosed in double quotes will be considered literal (with the quotes themselves removed). Unmatched quotes will be considered literal quotes. Example:
** {{ft|#time|"The month is" F}} &rarr; {{ #time: "The month is" F }}
** {{ft|#time|i's"}} &rarr; {{ #time: i's" }}
* Backslash escaping as in PHP's date() is supported. \H produces a literal H, \" produces a literal ".
 
More format codes may be added in the future, as demanded by the users of this extension. This may come in the form of either a more complete implementation of PHP's format codes, or additional "x" codes.
 
The format of the ''time'' parameter is identical to the one used by PHP's strtotime(). It supports both absolute and relative dates, such as "<tt>December 11</tt>" and/or "<tt>+10 hours</tt>", which can be used for timezone translation. Please see [http://www.gnu.org/software/tar/manual/html_node/tar_109.html the GNU tar manual] for more information.
 
====Examples====
*{{ft|#time|<nowiki>l j F Y | 20070304</nowiki>}} gives "{{#time:l j F Y|20070304}}"
*{{ft|#time|<nowiki>l j F Y | 2007-3-4</nowiki>}} gives "{{#time:l j F Y|2007-3-4}}"
*{{ft|#time|<nowiki>l j F Y | 4 March 2007</nowiki>}} gives "{{#time:l j F Y|4 March 2007}}"
*[[{{ft|#time|<nowiki>j F Y | 4 March 2007</nowiki>}}]] gives "[[{{#time:j F Y|4 March 2007}}]]"
*{{ft|#time|<nowiki>l j F Y | -14 days</nowiki>}} gives "{{#time:l j F Y|-14 days}}" (14 days ago)
*{{ft|#time|<nowiki>H:i | +6 hours</nowiki>}} gives "{{#time:H:i|+6 hours}}" (6 hours later than UTC)
*{{ft|#time|<nowiki>H:i | 8:15 +6 hours</nowiki>}} gives "{{#time:H:i|8:15 +6 hours}}"
*{{ft|#time|<nowiki>m/Y | -1 months</nowiki>}} gives "{{#time:m/Y|-1 months}}" (1 month ago)
 
In combination with [[Help:Date formatting and linking|user-specified date formatting]]:
*{{ft|#time|<nowiki>l| 4 March 2007</nowiki>}} [[{{ft|#time|<nowiki>j F| 4 March 2007</nowiki>}}]][[{{ft|#time|<nowiki>Y | 4 March 2007</nowiki>}}]] gives {{#time:l| 4 March 2007}} [[{{#time:j F| 4 March 2007}}]][[{{#time:Y |4 March 2007}}]]
*{{ft|#time|<nowiki>l| 4 March 2007</nowiki>}} [[{{ft|#time|<nowiki>:Y-m-d|4 March 2007</nowiki>}}]] gives "{{#time:l| 4 March 2007}} [[{{#time:Y-m-d|4 March 2007}}]]"
 
Both give the user-specified format; the two are different if no preference has been specified.
 
====Range====
The range of proper functioning is 01 January 1970 00:00:01 through 19 January 2038 03:14:07, or 1 through <math>2^{31}-1</math> seconds after the start of 1970 (the [[w:en:Year 2038 problem|Year 2038 problem]]). For arbitrary dates that may exceed this range, use [[:Category:Date computing template|date computing templates]] such as {{tim|dowa}} instead.
 
====February 29====
Caution should be taken with February 29, as <nowiki>{{#time:j|February 29}}</nowiki> will vary with the year. For example
 
*{{ft|#time|<nowiki>j|February 29 2006</nowiki>}} gives {{#time:j|February 29 2006}}
*{{ft|#time|<nowiki>j|February 29 2008</nowiki>}} gives {{#time:j|February 29 2008}}
 
<h3 style="background: beige">#rel2abs:</h3>
 
{{ft|#rel2abs}} converts a relative path to an absolute path.
 
{{ft|#rel2abs|path}}
{{ft|#rel2abs|path &#124; base path}}
 
A relative path is a path starting with '/', './', '../'. or is containing '/../' or '/.' or is simply the strings  '..' or '.'.
if a <tt>base path</tt> is given, is should be defined in an absolute syntax.
 
Example:
*If standing in <tt>Help:Foo/bar</tt> and is calling {{ft|#rel2abs|../baz}}, the result will be <tt>{{ #rel2abs: ../baz | Help:Foo/bar }}</tt>
*If standing in <tt>Help:Foo</tt> and is calling {{ft|#rel2abs|../baz}}, the result will be <tt>{{ #rel2abs: ../baz | Help:Foo }}</tt>
*If standing in <tt>Help:Foo</tt> and is calling {{ft|#rel2abs|../../baz}}, the result will be <tt>{{ #rel2abs: ../../baz | Help:Foo }}</tt>
*If calling {{ft|#rel2abs|../baz &#124; Help:Bar/foo}}, the result will be <tt>{{ #rel2abs: ../baz | Help:Bar/foo }}</tt>
*If calling {{ft|#rel2abs|Help:Foo/bar/../baz}}, the result will be <tt>{{ #rel2abs: Help:Foo/bar/../baz }}</tt>
 
There is no checks if the path do exist, for that you might use {{ft|#ifexist}} in combination:
:{{ft|#ifexist|{{ft sub|#rel2abs|..}}<nowiki> | '..' exist | '..' does not exist</nowiki>}} gives <tt>{{ #ifexist: {{#rel2abs: .. }} | '..' exist | '..' does not exist }}</tt>
:{{ft|#ifexist|{{ft sub|#rel2abs|.}}<nowiki> | '.' exist | '.' does not exist</nowiki>}} gives <tt>{{ #ifexist: {{#rel2abs: . }} | '.' exist | '.' does not exist }}</tt>
 
== Caveats ==
Like other [[Help:parser function|parser function]]s the parser functions in this extension are affected by [[mediazilla:5678|5678]] in a predictable way. Summary: undefined parameters can be overwritten by ''corresponding'' parameters, for details see [[/5678]] and [[Help:Substitution#Corrupted_default_value|Substitution]]. Substitution is the only case where this is critical with respect to parameter defaults. It doesn't affect defined parameters.
 
===Substitution===
Applying "subst:" to a parser function works, provided that there is no space between "subst:" and "#". For details see [[Help:Substitution]].
Note that unless a technique like [[Help:Substitution#Optional substitution|optional substitution]] is used, substituting a template which uses a parser function does not replace that parser function with its result. This is often undesirable.
 
See also the previous section.
 
===Tables===
Currently wiki pipe table syntax doesn't work inside conditionals, but there are some workarounds.
* Hide the pipe from parser functions by putting it:
** in a template, e.g. {{tim|!}}
** within <<nowiki>nowiki>|</nowiki</nowiki>>
** as an html entity &amp;#124;
* Use html style table syntax instead of wiki style table syntax. (Note: [[mw:Manual:$wgUserHtml|$wgUserHtml]] must be true)
* See also [[Help:Table]], completely empty rows or columns are not displayed. Empty cells could be also transformed into dummy <tt>&amp;nbsp;</tt> cells on pages not affected by [[mediazilla:5569|5569]].
Note that "'''<tt>|</tt>'''" and "'''<tt>=</tt>'''" were always tricky within templates, this is no new issue.
 
If all else fails, try setting [http://www.mediawiki.org/wiki/Manual:%24wgUseTidy <code>$wgUseTidy=true;</code>] in your <code>LocalSettings.php</code>.
 
===Expressions===
*'''div''' is not integer division and is redundant, use '''/''' (slash) for real divisions.
*'''mod''' uses PHP's % operator, which is different from modulo-operators in all other programming languages, see also {{tim|mod}} and [[mediazilla:6068|6068]].
*'''mod''' sometimes returns wrong results for the same input values, see [[mediazilla:6356|6356]] and [[/MOD10000]]. ''Update: values less than 1E+12 are apparently not affected.'' 
*Valid [[#.23expr:|#expr:]] results like {{#expr: 0.0000001}} are not yet supported as '''#expr:''' input:
*:<nowiki>{{#expr:</nowiki>{{#expr:0.0000001}}<nowiki>}}</nowiki> yields ''{{#expr:{{#expr:0.0000001}}}}''.
*Under certain conditions '''round 0''' results in '''-0''' instead of '''0'''. For an expression '''x''' using '''0+(x)''' fixes this oddity.
 
===Conditional whitespace===
Because conditionals trim the leading and trailing whitespaces around pipe characters (like named, but unlike unnamed template parameters), inserting a conditional whitespace character is not always simple. If you only want to insert spaces, you can use the HTML entity <code>&amp;#32;</code>, which inserts "&#32;".
 
if you want to insert new lines or other whitespace, you can insert non-printing characters between the pipe and the whitespace:
 
<pre>first paragraph. {{#if:{{{paragraph}}}|<nowiki />
 
second paragraph.}}</pre>
 
first paragraph. {{#if:{{{paragraph}}}|<nowiki />
 
second paragraph.}}
 
==Code execution==
In the case of conditional parser functions (<tt>[[#.23if:|if]]</tt>,
<tt>[[#.23ifeq:|ifeq]]</tt>,
<tt>[[#.23ifexist:|ifexist]]</tt>,
<tt>[[#.23ifexpr:|ifexpr]]</tt>,
<tt>[[#.23switch:|switch]]</tt>), 
the wikitext for each case (then-part, else-part, etc.) is internally "executed"/"processed"/"evaluated" regardless of whether the condition is satisfied, although the resulting output depends on the condition. This concerns:
*the pre-expand include size (see [[w:Wikipedia:Template limits]])
*lists of links from, and pages included in, another page (on the edit box of the source page and [[Help:What links here|What links here]] of the target page, both based on the [[mw:pagelinks table|pagelinks table]] and the [[mw:templatelinks table|templatelinks table]])
*{{ml|Help:Administration|Protection|cascading page protection}} - a transclusion in the then-part or else-part etc. in a call of a conditional parser function in a cascade-protected page causes protection of the transcluded page regardless of the condition; see also [[Help:Cascading protection demo]]
*other, see e.g. [[VariablesExtension]]
 
One may want to reduce processing to the actually applicable wikitext, to reduce the pre-expand include size, to avoid inapplicable items in the lists of links and inclusions, and to avoid unnecessary cascading of protection. This can be done by using #ifexpr etc. to select a template or link target, and put the whole parser function call inside the braces or brackets, e.g. <nowiki>{{ {{</nowiki>#ifexpr:..|a|b}} | ''parameters'' }} instead of <nowiki>{{ #ifexpr:.. | {{a|</nowiki>''parameters''}} | <nowiki>{{</nowiki>b |''parameters''}} }}. If there is no else-part a dummy template such as {{tim|x0}} can be used:<nowiki>{{ {{</nowiki>#ifexpr:..|a|x0}} | ''parameters'' }} instead of <nowiki>{{ #ifexpr:.. | {{</nowiki>a|''parameters''}} }}. If the parameters of a and b are not the same the parser function can be split up into one for the then-part, and one with inverse condition with the else-part becoming then-part (or the same condition and only an else-part): <nowiki>{{ {{</nowiki>#ifexpr:..|a|x0}} | ''parameters of a'' }}<nowiki>{{ {{</nowiki>#ifexpr:..|x0|b}} | ''parameters of b'' }} instead of <nowiki>{{ #ifexpr:.. | {{a|</nowiki>''parameters of a''}} | <nowiki>{{</nowiki>b |''parameters of b''}} }}.
 
Similarly, in the case of links we can use <nowiki>[[ {{</nowiki>#ifexpr:..|a|b}} ]] instead of <nowiki>{{ #ifexpr:.. | [[a]] | [[b]] }}</nowiki>. If there is no else-part we can use <nowiki>{{#ifexpr:..|[[ {{</nowiki>#ifexpr:..|a}} ]] }} instead of <nowiki>{{ #ifexpr:.. | [[a]] }}</nowiki>. Thus we need to duplicate the condition.
 
== Installation ==
:''The Current version of '''ParserFunctions''' requires php5 to function.
 
Download both of these files and put them in a new directory called ''ParserFunctions'' in your [[Mediawiki extensions|extensions]] directory.
 
* [http://svn.wikimedia.org/svnroot/mediawiki/trunk/extensions/ParserFunctions/Expr.php Expr.php]
* [http://svn.wikimedia.org/svnroot/mediawiki/trunk/extensions/ParserFunctions/ParserFunctions.php ParserFunctions.php]
 
If you don't have php5 use these files instead (older revision):
* [http://svn.wikimedia.org/viewvc/mediawiki/trunk/extensions/ParserFunctions/Expr.php?revision=16633 Expr.php]
* [http://svn.wikimedia.org/viewvc/mediawiki/trunk/extensions/ParserFunctions/ParserFunctions.php?revision=16633 ParserFunctions.php]
 
Then put the following at the end of your [[mw:Manual:LocalSettings.php|LocalSettings.php]]:
 
require_once( "$IP/extensions/ParserFunctions/ParserFunctions.php" );
 
You can also browse the code tree here:
 
* [http://svn.wikimedia.org/viewvc/mediawiki/trunk/extensions/ParserFunctions/ ParserFunctions in MediaWiki SVN]
 
=== 1.8 and up ===
All the ParserFunctions work under 1.8 and up, also in the localised forms.
 
===1.7===
All the ParserFunctions work under 1.7, but only in English. However, the extension may cause problems when used together with the [[Cite]] extension; cf. [http://mail.wikipedia.org/pipermail/wikitech-l/2006-October/039159.html].
 
===1.6===
When including the ParserFunctions in 1.6, some notices may be shown. Removing the following line (line 10) in ParserFunctions.php fixes the problem:
 
<pre>$wgHooks['LanguageGetMagic'][]      = 'wfParserFunctionsLanguageGetMagic';</pre>
 
Most ParserFunctions (except #if, which does not work at all) work just as well on MediaWiki 1.6, but the syntax of ParserFunctions is without the '#' character. If you want to use the '#' character, find this section of [http://svn.wikimedia.org/viewvc/mediawiki/trunk/extensions/ParserFunctions/ParserFunctions.php?revision=14375&view=markup ParserFunctions.php]:
<pre><nowiki>
$wgParser->setFunctionHook( 'expr', array( &$wgExtParserFunctions, 'expr' ) );
$wgParser->setFunctionHook( 'if', array( &$wgExtParserFunctions, 'ifHook' ) );
$wgParser->setFunctionHook( 'ifeq', array( &$wgExtParserFunctions, 'ifeq' ) );
$wgParser->setFunctionHook( 'ifexpr', array( &$wgExtParserFunctions, 'ifexpr' ) );
$wgParser->setFunctionHook( 'switch', array( &$wgExtParserFunctions, 'switchHook' ) );
$wgParser->setFunctionHook( 'ifexist', array( &$wgExtParserFunctions, 'ifexist' ) );
</nowiki></pre>
 
Then, replace it with this:
 
<pre><nowiki>
$wgParser->setFunctionHook( '#expr', array( &$wgExtParserFunctions, 'expr' ) );
$wgParser->setFunctionHook( '#if', array( &$wgExtParserFunctions, 'ifHook' ) );
$wgParser->setFunctionHook( '#ifeq', array( &$wgExtParserFunctions, 'ifeq' ) );
$wgParser->setFunctionHook( '#ifexpr', array( &$wgExtParserFunctions, 'ifexpr' ) );
$wgParser->setFunctionHook( '#switch', array( &$wgExtParserFunctions, 'switchHook' ) );
$wgParser->setFunctionHook( '#ifexist', array( &$wgExtParserFunctions, 'ifexist' ) );
</nowiki></pre>
 
In some cases it just helps to add the default language to the header function on line 169
 
function wfParserFunctionsLanguageGetMagic( &$magicWords, $langCode='en' ) {
 
'''A simple fix for #if in this version''' -
 
Replace:
 
<pre><nowiki>
function ifHook( &$parser, $test = '', $then = '', $else = '' ) {
  if ($test !== '') {
</nowiki></pre>
 
on line 57 with:
 
<pre><nowiki>
function ifHook( &$parser, $test = '', $then = '', $else = '' ) {
  if ( (string)$test !== '' ){
</nowiki></pre>
 
== See also ==
*[[Help:Calculation]]
*[[Help:Magic words]]
*[[Help:Template]]
*{{mlmw|Extension:ParserFunctions (extended)}}
*[[MathStatFunctions]]
*[[VariablesExtension]]
*[[StringFunctions]]
*[[DynamicFunctions]]
*[[:m:Category:Templates using ParserFunctions]]
*[[:en:Category:Templates using ParserFunctions]]
*[[Extending_wiki_markup#Parser_functions|Adding parser functions]]
*[[mw:Extension:LoopFunctions]], [[bugzilla:2357]] - loop functionality
 
== External links ==
* [http://mail.wikipedia.org/pipermail/wikitech-l/2006-April/thread.html#34685 The discussion about the ParserFunctions in the Wikitech-l list archive]

Revision as of 19:03, 4 April 2007

ParserFunctionsFunction
Type: Parser Extension
Version
Version: N/A
Maturity: Beta/Stable
MediaWiki: > 1.6.8
Last Updated: 2006-11-21
Description

Template:!-

A collection of parsefunctions such as branching instructions and expression handler and time calculation unit.
MediaWiki extensions


MediaWiki extension ParserFunctions is a collection of parser functions (note the difference between the name of the collection, and the general term). These parser functions have a hash character in front of the function name, so they typically have the syntax:

Template:Ft

With Special:ExpandTemplates one can evaluate expressions with parser functions directly.

Functions

This module defines eight functions at present: expr, if, ifeq, ifexist, ifexpr, switch, time, and rel2abs.

#expr:

The accuracy and format of numeric results varies with the operating system of the server.

The expr function computes mathematical expressions based on permutations of numbers (or variables/parameters that translate to numbers) and operators. It does not work with strings; use ifeq below instead. The syntax is:

Template:Ft

A list of supported operators follows. For more details about the operator precedence see Help:Calculation, it's roughly (1) grouping (parentheses), (2) unary (+/- signs and NOT), (3) multiplicative (*, /, div, mod), (4) additive (+ and -), (5) round, (6) comparative (=, !=, <, >, etc.), (7) logical AND, (8) logical OR. Within the same precedence class operators are evaluated left to right. As always some redundant parentheses are better than erroneous terse code.

Operator Operation Example
none

Template:Ft = 1.2345678901234E+14

Template:Ft = 1.0E-6

( ) Grouping operators

Template:Ft = 259

+ Unary + sign

Template:Ft = 210

- Unary - sign (negation)

Template:Ft = 210

not Unary NOT, logical NOT

Template:Ft = 7
Template:Ft = 7

* Multiplication

Template:Ft = 210

/ Division, same as div

Template:Ft = 4.2857142857143

div Division, same as /,
no integer division

Template:Ft = 4.2857142857143
Template:Ft = 6

mod "Modulo", remainder of division after truncating both operands to an integer.
Caveat, div and mod are different from all programming languages.

Template:Ft = 2
Template:Ft = -2
Template:Ft = -2
Template:Ft = 0
Template:Ft = 2
Template:Ft = 2

+ Addition

Template:Ft = 37

- Subtraction

Template:Ft = 23

round Rounds off the number on the left to the power of 1/10 given on the right

Template:Ft = 4.286
Template:Ft = 4
Template:Ft = 3500

= Equality (numerical incl. logical)

Template:Ft = 0

<> Inequality, same as !=

Template:Ft = 1

!= Inequality, same as <>, logical xor

Template:Ft = 1

< Less than

Template:Ft = 0

> Greater than

Template:Ft = 1

<= Less than or equal to

Template:Ft = 0

>= Greater than or equal to

Template:Ft = 1

and Logical AND

Template:Ft = 0

or Logical OR

Template:Ft = 1

The boolean operators consider 0 to be "false" and any other number to be "true", on output "true" is shown as 1.

Numbers are given in decimal with "." for the decimal point. The formatnum: function can be used to change the decimal point to a comma for the appropriate locales. Scientific notation with E plus exponent is not yet supported on input for expressions, but used on output, for details see Help:Calculation.

#if:

The Template:Ft function is an if-then-else construct. The syntax is:

Template:Ft
Template:Ft

The applied condition is "The condition string is non-empty". Thus, if the condition string is empty or consists only of whitespace, then the condition is false, and the else text is returned. Otherwise, the then text is returned. The else text may be omitted, in which case the result will be blank if the condition is false.

An example:

Template:Ft

Note that the condition string is not itself a condition such as "1 = 2"; for example, Template:Ft will return "yes", because the string "1 = 2" is not blank. Thus the Template:Ft function does not support "=" signs or mathematical expressions.

#ifeq:

Template:Ft compares two strings or numbers, and returns another string depending on the result of that comparison. The syntax is:

Template:Ft

If both strings can be interpreted as numbers the comparison is numerical. To force a string comparison add tokens that can't be interpreted as numbers:

Template:Ft gives 1
Template:Ft gives 0

Comparison of strings is case-sensitive:

Template:Ft gives 0
For compatibility with older templates #if: cannot directly distinguish defined and undefined parameter values, it's a shorthand for a comparison with the empty string. With #ifeq: it's directly possible to identify undefined parameters:
Template:Ft = blank,
Template:Ft = blank,
Template:Ft = undefined.
An undefined parameter without default counts in the comparison as a string consisting of the tag:
Template:Ft = 0.

#ifexist:

Template:Ft returns one of two results based on whether or not a named title exists.

Template:Ft


The usual case-sensitivity applies: if a page exists then also a non-canonical name for that page gives a positive result. E.g. on Meta:

Template:Ft gives RFC 3092, because Bugs exists
Template:Ft gives RFC 3092, because bugs is in canonical form the existing Bugs
Template:Ft gives RFC 3092 because BUGS does not exist
Template:Ft gives Oops although m:Help:Calculation exists, because of the interwiki prefix.

The first parameter is the title to check for, the second is the positive result, and the third, the negative result. If the parameter passed does not produce a valid title object, then the result is negative.

Template:Tim gives the same result, except that the result is positive for an interwiki link. You can also handle an interwiki link differently with Template:Tim.

Template:Ft doesn't handle relative paths (like '../foo'), for that, use it in combination of Template:Ft.

#ifexpr:

Template:Ft evaluates a mathematical expression and returns one of two strings depending on the result.

Template:Ft


If the expression evaluates to zero, then the else text is returned, otherwise the then text is returned. Expression syntax is the same as for expr.

At the moment the else text is also returned for an empty expression:
Template:Ft gives or else
Omitting both then text and else text gives no output except possibly an error message; this can be used to check the correctness of an expression, or to check the wording of the error message (emulated assertions, forced errors):
Template:Ft Division by zero. -- no result, hence "1/{{#ifeq: {{ns:4}}|Meta|1|0}}" is a correct expression
Template:Ft Division by zero.
Template:Ft correct -- "1=2" is a correct Boolean expression (not to be confused with one with the value 1, representing "true")
Template:Ft correct -- "1E2" not allowed in expressions
Template:Ft wrong -- "1/0" not allowed
Template:Ft wrong ("a=b" not allowed, to compare strings use #ifeq)

Example of an application: {{ #if: {{#ifexpr: {{PAGENAME}} }} || action if PAGENAME is a number (or correct numeric expression) }}

For another application, see also Template:Tim.

#switch:

switch compares a single value against multiple others, returning a string if a match is found. The syntax is basically:

Template:Ft begin <comparison value>
 | <value1> = <result1>
 | <value2> = <result2>
 | ...
 | <valuen> = <resultn>
 | <default result>
Template:Ft end

switch will search through each value passed until a match is found with the comparison value. When found, the result for that value is returned (the text string after the equal sign). If no match is found, but the last item has no equal sign in it, it will be returned as the default result. If your default result must have an equal sign, you may use #default:

Template:Ft begin <comparison value>
 | <value> = <result>
 | #default = <default result>
Template:Ft end

Note that it's also possible to have "fall through" for values (reducing the need to duplicate results). For example:

Template:Ft begin <comparison value>
| <value1>
| <value2>
| <value3> = <result3>
| ...
| <valuen> = <resultn>
| <default result>
Template:Ft end

Note how value1 and value2 contain no equal sign. If they're matched, they are given the result for value3 (that is, whatever is in result3).

As for #ifeq: the comparison is numerical where possible:
Template:Ft gives Yes
Template:Ft gives No
The matched value can be empty, therefore the following constructs are equivalent:
Template:Ft gives empty
Template:Ft gives empty

Comparison of strings is case-sensitive:

Template:Ft gives UPPER
Template:Ft gives UPPER
Template:Ft gives lower

This is not to be confused with the fact that parser function names are case-insensitive:

Template:Ft gives UPPER

To have the #switch statement be case-insensitive, use the construct {{lc:}} or {{uc:}}

Template:Ft gives lower
Template:Ft gives lower
Template:Ft gives lower

This is usually used in templates, when you want to have case-insensitivity on in param values:

Template:Ft begin Template:Ft sub
| a
| b
| c = '''''abc''' or '''ABC'''''
| A
| B
| C = ''Memory corruption due to cosmic rays''
| #default = N/A
Template:Ft end

gives abc or ABC

#switch may be used instead of #ifeq:

Template:Ft gives true
Template:Ft gives true

#time:

Template:Ft is a time and date formatting function. The syntax is:

Template:Ft
Template:Ft

If the time is not specified, the time at which the article is converted to HTML is used. Note that due to caching, this may be up to a week different to the time at which the article is viewed. Manual updates may be required, this can be achieved by saving the page without making any changes (a "null edit") or viewed with action=purge in search string of URL or viewed by a user whose option is "Disable page caching".

The format parameter is a format string similar to the one used by PHP's date.

The following format codes have the same meaning as in PHP. Significant differences from PHP's behaviour, apart from internationalisation (i.e. language and locale differences), should be considered an error of ParserFunctions and should be reported. All numeric format codes return numbers formatted according to the local language, use the xn code described below to override this.

Code Description Example output Current output
Year:
Y The 4-digit year. e.g. 2006 2024
y The 2-digit year. 00 to 99, e.g. 06 for year 2006. 24
Month:
n The month number, not zero-padded. 1 to 12 5
m The month number, zero-padded. 01 to 12 05
M An abbreviation of the month name. Often internationalised. Jan to Dec May
F The full month name. Often internationalised. January May
Week:
W ISO 8601 week number (ISO years have full weeks from monday to sunday, and ISO week number 1 always contains January 4 or the first thursday of the civil year), zero-padded. 01 to 52 or 53 (depends on year) 19
Day:
j The day of the month, not zero-padded. 1 to 31 7
d The day of the month, zero-padded. 01 to 31 07
z The day of the year (starting from 0) 0 to 364, or 365 on a leap year 127
D An abbreviation for the day of the week. Rarely internationalised. Mon to Sun Tue
l The full weekday name. Rarely internationalised. Monday to Sunday Tuesday
N ISO 8601 day of the week (according to the ISO 8601 week). 1 (for Monday) through 7 (for Sunday) 2
w number of the day of the week (according to the American week). 0 (for Sunday) through 6 (for Saturday) 2
Hour:
a am (between 01:00:00 and 12:59:59 on the same day) or pm, with lowercase (used with the 12-hour format). am or pm am
A Same as with code a above, but with uppercase. AM or PM AM
g 12-hour format of the hour without leading zeros (one or two digits, used with am/pm or AM/PM). 1 to 12 7
h 12-hour format of the hour, with leading padding zero (two digits, used with am/pm or AM/PM). 01 to 12 07
G 24-hour format of the hour, without leading padding zero (one or two digits). 0 to 23 7
H 24-hour format of the hour, with leading padding zero (two digits). 00 to 23 07
Minutes and seconds:
i The minute, with leading padding zero (two digits). 00 to 59 25
s The second, with leading padding zero (two digits). 00 to 59 38
U Seconds since January 1 1970 00:00:00 GMT. 0 to infinite 1715066738
Miscellaneous:
L Whether it's a leap year. 1 if it is a leap year, 0 otherwise. 1
t Number of days in the month. 28 to 31 31
c ISO 8601 formatted date, same as {{#time:Y-m-dTH:i:s{{#time:+H:i|+0 hours}}}}. fixed length string 2024-05-07T07:25:38+00:00
r RFC 2822 formatted date, same as {{#time:D, j M Y H:i:s {{#time:+H:i|+0 hours}}}}. variable length string Tue, 07 May 2024 07:25:38 +0000

The following format codes are extensions to the PHP syntax:

Code Description
xn Format the next numeric code as a raw ASCII number. For example, in the Hindi language, Template:Ft produces ०६, 06.
xN Toggle a permanent raw number formatting flag. Like xn, except it lasts until the end of the string or until the same code appears again.
xr Format the next numeric code as a roman numeral. Only works for numbers up to 3000.
xg Output the genitive form of the month name, for languages which make such a distinction between genitive and nominative.
xx A literal "x"

Any unrecognised character will be passed through to the output unmodified. There are also two quoting conventions which can be used to output literal characters.

  • Characters enclosed in double quotes will be considered literal (with the quotes themselves removed). Unmatched quotes will be considered literal quotes. Example:
  • Backslash escaping as in PHP's date() is supported. \H produces a literal H, \" produces a literal ".

More format codes may be added in the future, as demanded by the users of this extension. This may come in the form of either a more complete implementation of PHP's format codes, or additional "x" codes.

The format of the time parameter is identical to the one used by PHP's strtotime(). It supports both absolute and relative dates, such as "December 11" and/or "+10 hours", which can be used for timezone translation. Please see the GNU tar manual for more information.

Examples

In combination with user-specified date formatting:

Both give the user-specified format; the two are different if no preference has been specified.

Range

The range of proper functioning is 01 January 1970 00:00:01 through 19 January 2038 03:14:07, or 1 through seconds after the start of 1970 (the Year 2038 problem). For arbitrary dates that may exceed this range, use date computing templates such as Template:Tim instead.

February 29

Caution should be taken with February 29, as {{#time:j|February 29}} will vary with the year. For example

#rel2abs:

Template:Ft converts a relative path to an absolute path.

Template:Ft
Template:Ft

A relative path is a path starting with '/', './', '../'. or is containing '/../' or '/.' or is simply the strings '..' or '.'. if a base path is given, is should be defined in an absolute syntax.

Example:

  • If standing in Help:Foo/bar and is calling Template:Ft, the result will be Help:Foo/baz
  • If standing in Help:Foo and is calling Template:Ft, the result will be baz
  • If standing in Help:Foo and is calling Template:Ft, the result will be Error: Invalid depth in path: "Help:Foo/../../baz" (tried to access a node above the root node).
  • If calling Template:Ft, the result will be Help:Bar/baz
  • If calling Template:Ft, the result will be Help:Foo/baz

There is no checks if the path do exist, for that you might use Template:Ft in combination:

Template:Ft gives '..' does not exist
Template:Ft gives '.' exist

Caveats

Like other parser functions the parser functions in this extension are affected by 5678 in a predictable way. Summary: undefined parameters can be overwritten by corresponding parameters, for details see /5678 and Substitution. Substitution is the only case where this is critical with respect to parameter defaults. It doesn't affect defined parameters.

Substitution

Applying "subst:" to a parser function works, provided that there is no space between "subst:" and "#". For details see Help:Substitution. Note that unless a technique like optional substitution is used, substituting a template which uses a parser function does not replace that parser function with its result. This is often undesirable.

See also the previous section.

Tables

Currently wiki pipe table syntax doesn't work inside conditionals, but there are some workarounds.

  • Hide the pipe from parser functions by putting it:
    • in a template, e.g. Template:Tim
    • within <nowiki>|</nowiki>
    • as an html entity &#124;
  • Use html style table syntax instead of wiki style table syntax. (Note: $wgUserHtml must be true)
  • See also Help:Table, completely empty rows or columns are not displayed. Empty cells could be also transformed into dummy &nbsp; cells on pages not affected by 5569.

Note that "|" and "=" were always tricky within templates, this is no new issue.

If all else fails, try setting $wgUseTidy=true; in your LocalSettings.php.

Expressions

  • div is not integer division and is redundant, use / (slash) for real divisions.
  • mod uses PHP's % operator, which is different from modulo-operators in all other programming languages, see also Template:Tim and 6068.
  • mod sometimes returns wrong results for the same input values, see 6356 and /MOD10000. Update: values less than 1E+12 are apparently not affected.
  • Valid #expr: results like 1.0E-7 are not yet supported as #expr: input:
    {{#expr:1.0E-7}} yields 1.0E-7.
  • Under certain conditions round 0 results in -0 instead of 0. For an expression x using 0+(x) fixes this oddity.

Conditional whitespace

Because conditionals trim the leading and trailing whitespaces around pipe characters (like named, but unlike unnamed template parameters), inserting a conditional whitespace character is not always simple. If you only want to insert spaces, you can use the HTML entity &#32;, which inserts " ".

if you want to insert new lines or other whitespace, you can insert non-printing characters between the pipe and the whitespace:

first paragraph. {{#if:{{{paragraph}}}|<nowiki /> 

second paragraph.}}

first paragraph.

second paragraph.

Code execution

In the case of conditional parser functions (if, ifeq, ifexist, ifexpr, switch), the wikitext for each case (then-part, else-part, etc.) is internally "executed"/"processed"/"evaluated" regardless of whether the condition is satisfied, although the resulting output depends on the condition. This concerns:

One may want to reduce processing to the actually applicable wikitext, to reduce the pre-expand include size, to avoid inapplicable items in the lists of links and inclusions, and to avoid unnecessary cascading of protection. This can be done by using #ifexpr etc. to select a template or link target, and put the whole parser function call inside the braces or brackets, e.g. {{ {{#ifexpr:..|a|b}} | parameters }} instead of {{ #ifexpr:.. | {{a|parameters}} | {{b |parameters}} }}. If there is no else-part a dummy template such as Template:Tim can be used:{{ {{#ifexpr:..|a|x0}} | parameters }} instead of {{ #ifexpr:.. | {{a|parameters}} }}. If the parameters of a and b are not the same the parser function can be split up into one for the then-part, and one with inverse condition with the else-part becoming then-part (or the same condition and only an else-part): {{ {{#ifexpr:..|a|x0}} | parameters of a }}{{ {{#ifexpr:..|x0|b}} | parameters of b }} instead of {{ #ifexpr:.. | {{a|parameters of a}} | {{b |parameters of b}} }}.

Similarly, in the case of links we can use [[ {{#ifexpr:..|a|b}} ]] instead of {{ #ifexpr:.. | [[a]] | [[b]] }}. If there is no else-part we can use {{#ifexpr:..|[[ {{#ifexpr:..|a}} ]] }} instead of {{ #ifexpr:.. | [[a]] }}. Thus we need to duplicate the condition.

Installation

The Current version of ParserFunctions requires php5 to function.

Download both of these files and put them in a new directory called ParserFunctions in your extensions directory.

If you don't have php5 use these files instead (older revision):

Then put the following at the end of your LocalSettings.php:

require_once( "$IP/extensions/ParserFunctions/ParserFunctions.php" );

You can also browse the code tree here:

1.8 and up

All the ParserFunctions work under 1.8 and up, also in the localised forms.

1.7

All the ParserFunctions work under 1.7, but only in English. However, the extension may cause problems when used together with the Cite extension; cf. [1].

1.6

When including the ParserFunctions in 1.6, some notices may be shown. Removing the following line (line 10) in ParserFunctions.php fixes the problem:

$wgHooks['LanguageGetMagic'][]       = 'wfParserFunctionsLanguageGetMagic';

Most ParserFunctions (except #if, which does not work at all) work just as well on MediaWiki 1.6, but the syntax of ParserFunctions is without the '#' character. If you want to use the '#' character, find this section of ParserFunctions.php:

 $wgParser->setFunctionHook( 'expr', array( &$wgExtParserFunctions, 'expr' ) );
 $wgParser->setFunctionHook( 'if', array( &$wgExtParserFunctions, 'ifHook' ) );
 $wgParser->setFunctionHook( 'ifeq', array( &$wgExtParserFunctions, 'ifeq' ) );
 $wgParser->setFunctionHook( 'ifexpr', array( &$wgExtParserFunctions, 'ifexpr' ) );
 $wgParser->setFunctionHook( 'switch', array( &$wgExtParserFunctions, 'switchHook' ) );
 $wgParser->setFunctionHook( 'ifexist', array( &$wgExtParserFunctions, 'ifexist' ) );

Then, replace it with this:

 $wgParser->setFunctionHook( '#expr', array( &$wgExtParserFunctions, 'expr' ) );
 $wgParser->setFunctionHook( '#if', array( &$wgExtParserFunctions, 'ifHook' ) );
 $wgParser->setFunctionHook( '#ifeq', array( &$wgExtParserFunctions, 'ifeq' ) );
 $wgParser->setFunctionHook( '#ifexpr', array( &$wgExtParserFunctions, 'ifexpr' ) );
 $wgParser->setFunctionHook( '#switch', array( &$wgExtParserFunctions, 'switchHook' ) );
 $wgParser->setFunctionHook( '#ifexist', array( &$wgExtParserFunctions, 'ifexist' ) );

In some cases it just helps to add the default language to the header function on line 169

function wfParserFunctionsLanguageGetMagic( &$magicWords, $langCode='en' ) {

A simple fix for #if in this version -

Replace:

 function ifHook( &$parser, $test = '', $then = '', $else = '' ) {
  if ($test !== '') {

on line 57 with:

 function ifHook( &$parser, $test = '', $then = '', $else = '' ) {
  if ( (string)$test !== '' ){

See also

External links