Help:Extension:ParserFunctions/vi

Phần mở rộng cung cấp thêm 11 hàm phân tích cú pháp (parser functions, sau đây gọi ngắn gọn là hàm phân tích), bổ sung cho "" đã có sẵn trong MediaWiki. (Ngoài ra, lập trình viên có thể thiết lập để bổ sung thêm các hàm phân tích khác nữa dành cho việc xử lí xâu kí tự; những hàm này được miêu tả tại .) Tất cả các hàm phân tích cung cấp bởi phần mở rộng này đều có dạng:

#expr
Hàm này thực hiện biểu thức toàn học và trả về giá trị nó tính được. Hàm này cũng có sẵn trong thông qua hàm.



Các toán tử được liệt kê ở bên phải, theo thứ tự ưu tiên thực hiện. Xem Trợ giúp:Tính toán để biết chi tiết về chức năng của mỗi toán tử. Mức độ chính xác và cách định dạng của kết quả trả về phụ thuộc vào hệ điều hành của máy chủ chạy wiki, và cách định dạng số của ngôn ngữ của trang web đó.

Khi tính toán sử dụng đại số Boole, giá trị không (0) trả về  và bất kì giá trị nào khác không, kể cả âm hay dương, trả về  :



Nhập vào một biểu thức trống sẽ trả về một xâu kí tự rỗng. Nhập vào một biểu thức không hợp lệ sẽ trả về một thông báo lỗi, các thông báo lỗi có thể được nhận ra dùng hàm :



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



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



Làm tròn số
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.

Để chủ động làm tròn lên hoặc xuống, sử dụng lần lượt  hoặc.

Xâu
Biểu thức chỉ hoạt động với các giá trị kiểu số, chúng không thể so sánh các xâu hoặc kí tự. có thể được dùng thay vào đó.



#if
Hàm này kiểm tra một xâu thử xem nó rỗng hay không. Một xâu thử chứa chỉ toàn các kí tự trắng cũng được xem là rỗng.





Hàm này trước tiên kiểm tra xem tham số thứ nhất rỗng hay không. Nếu tham số thứ nhất không rỗng, hàm sẽ trả về tham số thứ hai. Nếu tham số thứ nhất rỗng hoặc chỉ chứa các kí tự trắng (khoảng trắng, dấu xuống dòng, v.v...), hàm sẽ trả về tham số thứ ba.



Xâu thử luôn luôn được hiểu là văn bản thuần (pure text), vì thế các biểu thức toán học không được thực hiện:



Tham số cuối cùng (false) có thể để trống:



Hàm này có thể được lồng vào nhau. Muốn vậy, đưa một hàm #if ở dạng đầy đủ vào vị trí một tham số của một hàm #if khác. Có thể lên tới 7 cấp độ làm tổ, tuy nhiên điều này có thể phụ thuộc vào wiki hoặc giới hạn bộ nhớ.

Bạn cũng có thể dùng một tham số làm xâu thử trong lần gọi. Hãy nhớ đừng quên thêm  (dấu sổ thẳng, dấu sổ dọc) sau tên của biến. (Để nếu tham số cuối cùng không có giá trị, nó sẽ được đánh giá thành một xâu rỗng thay ví xâu " ".)



Xem để xem thêm các ví dụ khác về parser function này.

#ifeq
Hàm phân tích cú pháp này so sánh hai xâu đầu vào, xác định xem chúng có giống nhau hay không và trả về một trong hai xâu dựa trên kết quả. Nếu cần so sánh nhiều hơn và có xâu đầu ra, hãy cân nhắc sử dụng.



Nếu cả hai xâu là các giá trị số hợp lệ, chúng được so sánh như hai số:



Ngược lại, chúng được so sánh như hai văn bản; việc so sánh là phân biệt hoa thường (case sensitive):


 * →  (so sánh với ví dụ tương tự ở trên, không có ngoặc kép)
 * →  (so sánh với ví dụ tương tự ở trên, với   trả về một số hợp lệ trước tiên)
 * →  (so sánh với ví dụ tương tự ở trên, không có ngoặc kép)
 * →  (so sánh với ví dụ tương tự ở trên, với   trả về một số hợp lệ trước tiên)

Để làm ví dụ thực tế, hãy xem xét   hiện có bằng cách sử dụng trình phân tích cú pháp để chọn giữa hai thời điểm chuẩn, ngắn và dài. Nó nhận tham số này làm đầu vào đầu tiên để so sánh với xâu "short"– không có quy ước nào về thứ tự, nhưng sẽ dễ đọc hơn nếu tham số này đứng trước. Mã bản mẫu được định nghĩa là:



khi đó:


 * → 20
 * → 40
 * → 40

#iferror
Hàm này nghiên cứu xâu được nhập vào và trả về một trong hai kết quả; hàm này xem xâu là  nếu xâu có chứa một object HTML với , tạo ra bởi các parser functions khác như  ,   và  , các lỗi bản mẫu như lặp (loops) và đệ quy (recursion), cũng như các lỗi "failsoft" parser khác.



Một hoặc cả hai giá trị trả về có thể được để trống. Nếu  được để trống và hàm xác định xâu đưa vào là không lỗi, hàm sẽ trả về chính xâu đó. Nếu  được để trống, khi gặp lỗi hàm sẽ trả về một xâu rỗng.


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

Some errors may cause a tracking category to be added, using  will not suppress the addition of the category.

#ifexpr
Hàm này tính toán giá trị của biểu thức toán học đưa vào và trả về một trong hai xâu phụ thuộc vào giá trị boole (đúng/sai) của kết quả:



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



comparing



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



Boolean operators of equality or inequality operators are supported.



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



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.

does not work with interwiki links.



Giới hạn của ifexist
được coi là một "hàm phân tích tốn kém"; chỉ một số lượng giới hạn có thể được nhúng vào bất kì một trang nào (bao gồm các hàm trong các bản mẫu được truyền tải). Khi đạt đến giới hạn, những hàm  chạy sau sẽ tự động trả về false false, dù trang mục tiêu có tồn tại hay không, và trang đó sẽ được đưa vào Category:. Tên của có thể khác nhau tuỳ thuộc vào ngôn ngữ nội dung của wiki của bạn.

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 does not exist and is tested for using #ifexist will end up on the Wanted Pages. See for the reason, and w:Template:Linkless exists for a workaround.

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



For a similar group of functions see also Help:Magic words#URL data. Built-in parser functions include: 'localurl:', 'fullurl:', 'anchorencode:' etc.

#switch
 See also: w:Help:Switch parser function

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

Examples:




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

Mặc định
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 (an equals sign without ). If it does, it will be treated as a case comparison, and no text will display if no cases match. This is because the default value has not been defined (is empty). If a case matches however, its associated string will be returned.



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:



Grouping results
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. The " " in the last parameter may be omitted in the above case.



Sử dụng với tham số
The function may be used with parameters as the test string. In this case, it is not necessary to place the pipe after the parameter name, because it is very unlikely that you will choose to set a case to be the string " ". ( This is the value the parameter will default to if the pipe is absent and the parameter doesn't exist or have a value. See . )



In the above case, if  equals , the function will return. If it equals, the function will return. If the parameter is empty or does not exist, the function will return.

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



Here, if  equals ,   or  , the function will return. If it equals, the function will return. If the parameter is empty or does not exist, the function will return.

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



In this case, the function returns an empty string unless  exists and equals   or , in which case it returns   or  , respectively.

This has the same effect as declaring the default result as empty.



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


 * (when  doesn't exist or is empty):
 * →  Foo 
 * (when  has the value " "):
 * →  Bar 
 * (when  has the value " "):
 * →  Foo 

In this hypothetical case, you would need to add the pipe to the parameter.



Hành vi so sánh
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:



Raw equal signs
"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.

Example:

Replacing #ifeq
can be used to reduce expansion depth.

For example:



is equivalent to



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.

As the list of formatting codes continues to evolve (with the support of new calendars, or of new date fields computed and formatted differently), you should escape all literal characters (not just ASCII letters currently used by formatting codes) that need to be passed through unaltered.

Unfortunately, for now, the ASCII single quote is still not recognized as a simple alternative for marking literal text to the currently supported ASCII double quotes (for example, double quotes are mandatory for in other uses like the delimitation of string values in JSON, C, C++...) and backslashes (which have to be escaped as well in string constants used by many languages, including JSON, C, C++, PHP, JavaScript, Lua). So you still cannot embed any literal double quote without escaping it with a backslash (or you can use other curly, angular or square quotation marks instead).



The  can be in any format accepted by PHP's strtotime function. Absolute (e.g. ), relative (e.g.  ), and combined times (e.g.  ) 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:



A four-digit number is always interpreted as a year, never as hours and minutes:



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


 * →  Input is treated as a time rather than a year+month code.
 * →  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:



The total length of the format strings of the calls of  is limited to 6000 characters.

Time Zone issue
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:


 * &rarr;

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:


 * &rarr;

To workaround this issue, simply convert the time into minutes or seconds, like this:


 * &rarr;
 * &rarr;

(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 occurrence 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.

}}

StringFunctions
All of these functions are integrated from the StringFunctions extension, but are only available if an administrator sets   in.

All of these functions operate in O(n) time complexity, making them safe against DoS attacks.

#len
The #len function returns the length of the given string. The syntax is:

The return value is always a number of characters in the source string (after expansions of template invocations, but before conversion to HTML). If no string is specified, the return value is zero.

#pos
The #pos function returns the position of a given search term within the string. The syntax is:

The offset parameter, if specified, tells a starting position where this function should begin searching.

If the search term is found, the return value is a zero-based integer of the first position within the string.

If the search term is not found, the function returns an empty string.

#rpos
The #rpos function returns the last position of a given search term within the string. The syntax is:

If the search term is found, the return value is a zero-based integer of its last position within the string.

If the search term is not found, the function returns -1.

#sub
The #sub function returns a substring from the given string. The syntax is:

The start parameter, if positive (or zero), specifies a zero-based index of the first character to be returned.

Example: returns.

returns.

If the start parameter is negative, it specifies how many characters from the end should be returned.

Example: returns.

The length parameter, if present and positive, specifies the maximum length of the returned string.

Example: returns.

If the length parameter is negative, it specifies how many characters will be omitted from the end of the string.

Example: returns.

If the start parameter is negative, it specifies how many characters from the end should be returned. The length parameter, if present and positive, specifies the maximum length of the returned string from the starting point.

Example: returns.

#count
The #count function returns the number of times a given substring appears within the provided text.

#replace
The #replace function returns the given string with all occurrences of a search term replaced with a replacement term.

If the search term is unspecified or empty, a single space will be searched for.

If the replacement term is unspecified or empty, all occurrences of the search term will be removed from the string.

Currently the syntax doesn't provide a switch to toggle case-sensitivity setting. But you may make use of magic words of formatting as a workaround. (e.g. ) For example, if you want to remove the word "Category:" from the string regardless of its case, you may type:
 * Case-insensitive replace :

But the disadvantage is that the output will become all lower-case. If you want to keep the casing after replacement, you have to use multiple nesting levels (i.e. multiple replace calls) to achieve the same thing.

#explode
The #explode function splits the given string into pieces and then returns one of the pieces. The syntax is:

The delimiter parameter specifies a string to be used to divide the string into pieces. This delimiter string is then not part of any piece, and when two delimiter strings are next to each other, they create an empty piece between them. If this parameter is not specified, a single space is used. The limit parameter is available in ParserFunctions only, not the standalone StringFunctions version, and allows you to limit the number of parts returned, with all remaining text included in the final part.

The position parameter specifies which piece is to be returned. Pieces are counted from 0. If this parameter is not specified, the first piece is used (piece with number 0). When a negative value is used as position, the pieces are counted from the end. In this case, piece number -1 means the last piece. Examples:


 * returns
 * returns
 * returns
 * returns

The return value is the position-th piece. If there are fewer pieces than the position specifies, an empty string is returned.

#urldecode
converts the escape characters from an 'URL encoded' string back to readable text. The syntax is:

Notes:
 * This function works by directly exposing PHP's urldecode function.
 * A character-code-reference can be found at www.w3schools.com.
 * The opposite,, has been integrated into MediaWiki as of version 1.18; for examples, see.
 * urldecode was merged from Stringfunctions in 2010, by commit 1b75afd18d3695bdb6ffbfccd0e4aec064785363

Limits
This module defines three global settings:


 * $wgStringFunctionsLimitSearch
 * $wgStringFunctionsLimitReplace
 * $wgStringFunctionsLimitPad

These are used to limit some parameters of some functions to ensure the functions operate in O(n) time complexity, and are therefore safe against DoS attacks.

$wgStringFunctionsLimitSearch
This setting is used by #pos, #rpos, #replace, and #explode. All these functions search for a substring in a larger string while they operate, which can run in O(n*m) and therefore make the software more vulnerable to DoS attacks. By setting this value to a specific small number, the time complexity is decreased to O(n).

This setting limits the maximum allowed length of the string being searched for.

The default value is 30 multibyte characters.

$wgStringFunctionsLimitReplace
This setting is used by #replace. This function replaces all occurrences of one string for another, which can be used to quickly generate very large amounts of data, and therefore makes the software more vulnerable to DoS attacks. This setting limits the maximum allowed length of the replacing string.

The default value is 30 multibyte characters.

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

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

Escaping pipe characters in tables
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:.

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.



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

Beware that not all parameters are created equal. In ParserFunctions, whitespace at the beginning and end is always stripped. In templates, whitespace at the beginning and end is stripped for named parameters and named unnamed parameters but not from unnamed parameters:


 * → foofoo
 * → foofoo
 * → foofoo