Help:Extension:ParserFunctions/pt

A extensão fornece onze funções adicionais ao analisador sintáctico, que suplementam as «» já presentes no MediaWiki (a extensão pode ser configurada para fornecer funções adicionais para o tratamento de texto; estas funções de texto estão documentadas ). Todas as funções fornecidas pela extensão têm a forma: (It may be configured to provide additional parser functions for string handling; these string functions are documented .) All the parser functions provided by this extension take the form:

#expr
Esta função calcula uma expressão matemática e devolve o valor calculado. A função também está disponível no através da função.



Os operadores disponíveis estão listados na tabela da direita, por ordem crescente de precedência. Consulte para mais detalhes sobre a função de cada operador. A exactidão e o formato do resultado devolvido dependem do sistema operativo do servidor que está a executar o MediaWiki, e do formato numérico da língua do site.

Nos operadores de álgebra booleana, o número zero assume o valor lógico  e qualquer outro número diferente de zero, positivo ou negativo, assume o valor lógico.



Uma expressão de entrada vazia devolve um texto vazio. Expressões inválidas devolvem uma das várias mensagens de erro, que podem ser apanhadas usando a função :



A ordem dos operandos de adição e subtracção antes ou depois de um número é significativa, e pode ser tratada como um valor positivo ou negativo em vez de como um operando com uma entrada errada:



Note que, ao usar o resultado de palavras mágicas, tem de formatá-las para remover vírgulas e traduzir os números. Por exemplo, resulta em, quando desejamos 0, que pode ser obtido por. Isto é especialmente importante nalgumas línguas em que os números são traduzidos. Por exemplo, na língua Bengali, produz ৩০,০৬১.



Arredondamento
Arredonda o número à sua esquerda para um múltiplo de 1/10 elevado a uma potência, com o expoente igual ao valor truncado do número à direita.

Para arredondar por excesso ou por defeito, use os operadores unários  ou   respetivamente.

Textos
As expressões só funcionam com valores semelhantes a números, não podem comparar textos (strings) nem caracteres. Em alternativa, pode usar-se.



#if
Esta função determina se um texto de teste tem conteúdo ou está vazio. Um texto de teste que só contém caracteres em branco (espaços, linhas novas, etc.) é considerado vazio.





Esta função testa se o primeiro parâmetro não está vazio. Se o primeiro parâmetro não estiver vazio a função apresenta o segundo argumento. Se o primeiro parâmetro estiver vazio ou contiver apenas caracteres em branco (espaços, linhas novas, etc.) ela apresenta o terceiro argumento.



O texto de teste é sempre interpretado como texto puro, portanto expressões matemáticas não são avaliadas:



O último parâmetro (falso) pode ser omitido:



A função pode ser intercalada. Para fazê-lo, coloque a função #if interior na sua forma integral, no lugar de um parâmetro da função #if exterior. É possível intercalar até uma profundidade de sete níveis, embora isto possa depender da wiki ou de um limite de memória.

Também pode usar um parâmetro como texto de teste na sua declaração #if. Tem de se certificar que adicionou a  (barra vertical) após o nome da variável.



Consulte para mais exemplos desta função.

#ifeq
Esta função do analisador sintático compara dois textos e determina se são idênticos.



Se ambos os textos são valores numéricos válidos, os textos são comparados numericamente:



Caso contrário, a comparação é feita como texto; esta comparação é sensível ao uso de maiúsculas e minúsculas:


 * →  (comparar com o exemplo semelhante acima, sem as aspas)
 * →   (comparar com o exemplo semelhante acima, com  ) 
 * →  (comparar com o exemplo semelhante acima, sem as aspas)
 * →   (comparar com o exemplo semelhante acima, com  ) 

Como exemplo prático, dada uma existente   usado para definir tamanhos curtos e longos padronizados, definidos como:



acontecerá o seguinte:


 * → 20
 * → 40
 * → 40

#iferror
Esta função recebe um texto de entrada e devolve um de dois resultados; resulta no valor  se o texto de entrada contém um objeto HTML com , tal como é gerado por outras funções do analisador sintático como  ,   e  , erros em predefinições como ciclos e recursividade, e outros erros do analisador sintático em modo de capacidade diminuída.



Podem ser omitidos um ou ambos os textos a devolver. Se o texto para  for omitido, é devolvido o   se este não estiver errado. Se o texto para  também for omitido, será devolvido um texto vazio em caso de erro:


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

#ifexpr
Esta função avalia uma expressão matemática e devolve um de dois textos, dependendo do valor booleano do resultado:



A  de entrada é avaliada exatamente como para   acima, estando disponíveis os mesmos operadores. A saída é então avaliada como uma expressão booleana.

Uma expressão de entrada vazia é avaliada como :



Como mencionado acima, zero é avaliado como  e qualquer valor diferente de zero é avaliado como , portanto esta função é equivalente a uma que use apenas   e  :



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 the return values may be omitted; no output is given when the appropriate branch is left empty:



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

ifexist limits
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.

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

Exemplos:




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

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



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

Comparison behavior
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.

Exemplo:





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.

Replacing #ifeq
can be used to reduce expansion depth.

Por exemplo: 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.



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 language code in ISO 639-3 (?) allows the string to be displayed in the chosen language

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:

However, Venezuela is on a -4.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, except that it uses the local time of the wiki (as set in ) when no date is given.





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

}}

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

Remoção de espaço vazio
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

Ver também

 * m:Help:Calculation
 * m:Help:Newlines and spaces
 * m:Help:Comparison between ParserFunctions syntax and TeX syntax
 * Module:String obsoleting
 * Module:String obsoleting
 * Module:String obsoleting