Help:Extension:ParserFunctions/zh

扩展提供11个附加解析器函数以补充MediaWiki固有的“”. （它有可能会配置到增加的解析器函数以支持运行：这些字符串函数已在记载. ） 所有的解析器函数由下列的表格提供.

#expr
这个函数计算并返回数学表达式的结果. 这个函数也通过 函数中在有效.



右表依优先级列出了支持的运算符，运算符的详细说明请见Help:Calculation. 运算结果的精度和格式受服务器操作系统及语言设置影响可能存在差异.

使用布尔代数时，0表示 ，其他任何非0数值（无论正负）均表示 ：



空表达式返回空值，错误的表达式返回错误信息，使用 函数检查错误：



置于数字前的加减号会被视为正负号而不会报错：



注意：使用魔术字输出的数值时，首先要将其格式化以去除逗号，获得纯数字. 例如： 输出，而期望的输出值是0，使用 便可以实现. 对于某些语言，格式化数字尤为重要. 例如孟加拉语中， 的输出结果是৩০,০৬১.



凑整
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  or   respectively.

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



#if
这个函数判断一个字符串是否为空. 只包含空格的字符串被视为空字符串.





这个函数首先判断参数1是否为空. 如果参数1不为空，则输出参数2. 如果参数1为空或只包含空白内容（空格、换行等），则输出参数3.



字符串内容会被处理为纯文本，因此数学表达式不会被计算：



最后一个参数（false）可能被忽略：



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.

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.



See for more examples of this parser function.

#ifeq
这个函数判断两个輸入字符串是否相同，並根據結果輸出兩個字符串的其中一個. 如果需要更多的比較和輸出字符串，請考慮使用.



如果两个字符串均为数字，则函数会进行数值的比较：



否则函数会进行文本的比较（大小写敏感）：


 * →  （对比上面没有引号的例子）
 * →  （对比上面带有 的例子，會先回傳一個有效的整數）
 * →  （对比上面没有引号的例子）
 * →  （对比上面带有 的例子，會先回傳一個有效的整數）

As a practical example, consider an existing   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:



因为以下的原因：


 * → 20
 * → 40
 * → 40

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



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


 * → &zwnj;
 * → &zwnj;
 * → &zwnj;
 * → &zwnj;
 * → &zwnj;
 * → &zwnj;

#ifexpr
此函数会判断数学表达式并根据其布尔值结果返回对应的字符串：



The  input is evaluated exactly as for   above, with the same operators being available. The output is then evaluated as a boolean expression.

An empty input expression evaluates to :



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



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 ).

比较

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



#ifexist
这个函数将一组字符串作为输入，并翻译成页面标题，然后根据在本地wiki上是否存在该页面而返回对应的值.



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



The function evaluates to  for  that have been customized, and for  that are defined by the software.



If a page checks a target using, then that page will appear in the  list for the target page. So if the code  were included live on this page, /Foo will list.

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

If a local description page has been created for the file, the result is exists for all of the above.

不会对维基内链起作用.

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  functions automatically return false, whether the target page exists or not, and the page is categorized into Category:. The name of the 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  (to select links to unexisting pages) or   (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, one can also increase the limit in LocalSettings.php if needed.

ifexist and wanted pages
A page that 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.



Within the  input, the following syntax is valid:
 * → the current level
 * → "go up one level"
 * → "go down one level into the subdirectory /foo"

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



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:



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

例如：




 * 1) switch with partial transclusion tags can effect a configuration file that enables an editor unfamiliar with template coding to view and edit configurable elements.

默认
The  is returned if no   string matches the  :



In this syntax, the default result must be the last parameter and must not contain a raw equals sign.



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

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



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



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

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

比较行为
As with, 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:





A  string may be empty:

Once a match is found, subsequent  are ignored:

原始等号
"Case" strings cannot contain raw equals signs. To work around this, create a template = containing a single equals sign:, or replace equals sign with html code.

例子：





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

替换#ifeq
can be used to reduce expansion depth.

例如： 等效于 i.e. deep nesting, linear:

On the other hand, the switch replacement could be complicated/impractical for IFs nested in both branches (shown with alternatives of indentation, indented on both sides), making full symmetrical tree:

#time
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  – that is, the time the page was last rendered into HTML.



The list of accepted formatting codes is given in the table to the right. Any character in the formatting string that is not recognized 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: In addition, the digraph  is interpreted as a single literal "x".
 * 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.



The  can be in any format accepted by PHP's strtotime function. Both absolute (eg ) and relative (eg  ) times are accepted.


 * &rarr; 
 * &rarr; 
 * &rarr; 
 * &rarr; 
 * &rarr; 
 * &rarr; 
 * &rarr; 

The  in ISO 639-3 (?) allows the string to be displayed in the chosen language

The  parameter specifies if the date/time object refers to the local timezone or to UTC.

This is a boolean parameters: its value is determined by casting the value of the argument (see the official PHP documentation for details on how string are cast to boolean values).

See the following examples for details:





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



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:



4位數字總是被解讀為年分，而不是小時和分鐘：

6位數字盡量被解讀為小時、分鐘、秒，不然會被解讀為錯誤（而不是年分和月分）：
 * →  輸入被視為時間而不是年+月代碼.
 * →  雖然19:60:09不是有效時間，但196009不被解讀為1960年9月.

該函數執行一定數量的日期算數：



調用的格式字符串的總長度限制為6000個字符.

时区问题
There is a bug in this #time parser function (more specifically in PHP DateTime) that does not allow the passing-in of non-integers as relative time zone offsets. This issue does not apply when using an on-the-hour time zone, such as EDT. For example:

However, India is on a +5.5 hours time offset from UTC, and thus using its time zone will not normally allow the correct calculation of a relative time zone offset. Here's what happens: To workaround this issue, simply convert the time into minutes or seconds, like this:

(Tim Starling, the developer of this function, provided the exact syntax for this solution.)

#timel
This function is identical to, when the   parameter is set to  , so it always uses the local time of the wiki (as set in ).

Syntax of the function is:



For instance, see the following examples:



#titleparts
This function separates a page title into segments based on slashes, then returns some of those segments as output.



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


 * →  See also.
 * →  See also.

Negative values are accepted for both values. Negative values for the number of segments to return parameter effectively 'strips' segments from the end of the string. Negative values for the first segment to return translates to "start with this segment counting from the right":


 * →  Strips one segment from the end of the string. See also.
 * →   Strips all 4 segments from the end of the string
 * →   Strips 5 segments from the end of the string (more than exist)
 * →   Returns last segment. See also.
 * →   Strips one segment from the end of the string, then returns the second segment and beyond
 * →   Start copying at the second last element; strip one segment from the end of the string

Before processing, the pagename parameter is HTML-decoded: if it contains some standard HTML character entities, they will be converted to plain characters (internally encoded with UTF-8, i.e. the same encoding as in the MediaWiki source page using this parser function).


 * For example, any occurence of,  , or   in pagename will be replaced by.
 * No other conversion from HTML to plain text is performed, so HTML tags are left intact at this initial step even if they are invalid in page titles.

Then the decoded pagename is canonicalized into a standard page title supported by MediaWiki, as much as possible:


 * 1) All underscores are automatically replaced with spaces:
 * →  Not bah_boo, despite the underscore in the original.
 * 1) 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:
 * 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:
 * 1) Finally the first substring is capitalized according to the capitalization settings of the local wiki (if that substring also starts by a local namespace name, that namespace name is also normalized).
 * 1) Finally the first substring is capitalized according to the capitalization settings of the local wiki (if that substring also starts by a local namespace name, that namespace name is also normalized).
 * 1) Finally the first substring is capitalized according to the capitalization settings of the local wiki (if that substring also starts by a local namespace name, that namespace name is also normalized).

{{Warning|1= Certain characters that are illegal in a page title will cause #titleparts to not parse the string:


 * → {{#titleparts: {one/two} | 1 | 1 }}. Does not produce the expected: {one
 * → {{#titleparts: page/123 | 1 | 2 }}. Does not work because brackets are illegal in page titles and this parser function does not process links embedded in its input pagename parameter, even when they use the MediaWiki syntax, or any other HTML or MediaWiki tags.
 * → "{{#titleparts: red/#00FF00/blue| 1 | 3 }}". Does not work because "#" is also illegal in page titles.

}}

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


 * → the code   will be inserted in the wikitext since the page exists.

Substitution does not work within, you can use &hellip;  for this purpose.

重定向
Especially   could be handy in  to pages including dates, but this does not work.

在表格中逸出的管道符
Parser functions will mangle syntax and pipe characters, treating all the raw pipe characters as parameter dividers. To avoid this, most wikis used a template    :! with its contents only a raw pipe character, since MW 1.24 a  replaced this kludge. 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. It will then be interpreted as a table row or column separator. Alternatively, raw HTML table syntax can be used, although this is less intuitive and more error-prone.

You can also escape the pipe character for display as a plain, uninterpreted character using an HTML entity:.

剥离空格
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.



To prevent the trimming of then and else parts, see m:Template:If. Some people achieve this by using &lt; &gt;  &lt; /nowiki &gt; instead of spaces.


 * → foofoo
 * → foofoo

However, this method can be used to render a single whitespace character only, since the parser squeezes multiple whitespace characters in a row into one.




 * || → || foofoo 
 * }

In this example, the  style is used to force the whitespace to be preserved by the browser, but even with it the spaces are not shown. This happens because the spaces are stripped by the software, before being sent to the browser.

It is possible to workaround this behavior replacing whitespaces with  (breakable space) or   (non-breakable space), since they are not modified by the software:


 * →  foofoo 
 * → foofoo

参见

 * m:Help:Calculation
 * m:Help:Newlines and spaces
 * m:Help:Comparison between ParserFunctions syntax and TeX syntax
 * Module:String已废弃的
 * Module:String已废弃的
 * Module:String已废弃的