Help:Extension:ParserFunctions/gl

A extensión fornece once funcións sintácticas adicionais para estender as "palabras máxicas", que xa forman parte de MediaWiki. Tódalas funcións sintácticas definidas nesta extensión asumen o seguinte paradigma:

#expr
Esta función calcula a expresión matemática e devolve o seu resultado.



Os operadores dispoñibles son clasificados á dereita, en orde de precedencia. Véxase para máis detalles da función de cada operador. A precisión e o formato do resultado devolto cambiará a depender do sistema operativo do servidor correndo a wiki, e o formato de número da linguaxe do sitio.

Cando avaliar usando álxebra booleana, o valor cero é avaliado coma  (falso) e calquera valor distinto de cero, positivo ou negativo, é avaliado coma   (verdadeiro):



Unha expresión de entrada baleira retorna un valor string baleiro. Expresións inválidas retornan unha das varias mensaxes de erro, que poden ser capturadas usando a función :



A orde de operandos de adición e subtracción antes ou despois de un número é significativa, podendo este ser tratado coma un valor positivo ou negativo en lugar dun operando cunha entrada errónea:



Nótese que, cando se utiliza a saída das palabras máxicas, débese formatalos en raw, para eliminar as comas e traducir os números. Por exemplo resulta dentro, na que se quer 0, cal pode ser obtido utilizando. Isto é especialmente importante nalgunhas linguas, nas que os números son traducidos. Por exemplo, en bengalí, produce ৩০,০৬১.



Redondeamento
Redondea o número á esquerda a un múltiple de 1/10 elevado a unha potencia, co expoñente igual ó valor truncado do número á dereita.

Para redondear para cima ou para baixo dédese usar os unarios ou , respectivamente.

#if
Esta función avalía un string de test e determina se está baleiro ou non. Considérase que un string de test que posúe soamente espazo en branco está baleiro.





Esta función primeiro proba se o primeiro parámetro non está baleiro. Se tal non está baleiro, a función mostra o segundo. Se o primeiro parámetro está baleiro ou contén soamente caracteres en branco (espazos, quebra de liña etc.), móstrase o terceiro.



String de test é sempre interpretado coma texto puro, así expresións matemáticas non son analizadas:



Calquera ou ambos os valores retornados poden ser omitidos:



A función pode ser agrupada. Para facer así, poña completamente a función #if interior no lugar do terceiro parámetro da función #if que se encerra. Unha profundidade de polo menos sete niveis de agrupamento é posible, aínda que iso pode depender da wiki ou do límite de memoria.
 * Exemplo: 

Véxase Help:Parser functions in templates para máis exemplos desta función.

#ifeq
Esta función compara dous strings e determina se son idénticos.



Se ambos os dous strings son valores numéricos válidos, son comparadas numericamente:



En caso contrario, a comparación é feita coma texto; esta comparación é sensible a letras maiúsculas:


 * →  (compare con exemplo similar arriba, sen comiñas)
 * →  (compare con exemplo similar arriba, con  )
 * →  (compare con exemplo similar arriba, sen comiñas)
 * →  (compare con exemplo similar arriba, con  )

Como un exemplo práctico, dado un modelo existente  usado para establecer tamaños estándares de curtos e longos, definido como:

resulta no seguinte:


 * → 20
 * → 40
 * → 40

#iferror
Esta función toma un string de entrada e devolve un de dous resultados. A función toma como  se a string de entrada contén un obxecto de HTML con , a medida que é xerado por outras funcións sintácticas, coma  ,   e  , erros de modelos coma bucles, recorrencias e outros erros sintácticos de "failsoft".



Un ou ambos os strings de retorno poden ser omitidos. Se o string  é omitido, o   é devolto se non estiver errado. Se o string  é tamén omitido, un string baleiro é devolto nun erro:


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

#ifexpr
Esta función avalía unha expresión matemática e devolve un de dous strings, dependendo do valor binario do resultado:



A entrada de  é avaliada exactamente como está por   arriba, cos mesmos operadores que están dispoñibles. A saída é entón avaliada como sendo unha expresión binaria.

Unha expresión de entrada baleira avalía cara :



Como mencionado arriba, cero avalía cara  e calquera valor non cero avalía cara , así esta función é equivalente a unha utilizando soamente   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 ).

comparando

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



#ifex
This function evaluates a mathematical expression and returns the calculated value.



The available operators are listed to the right, in order of precedence. See for more details of the function of each operator. The accuracy and format of the result returned will vary depending on the operating system of the server running the wiki, and the number format of the site language.

When evaluating using, zero evaluates to  and any nonzero value, positive or negative, evaluates to  :



An empty input expression returns an empty string. Invalid expressions return one of several error messages, which can be caught using the  function:



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 ৩০,০৬১.



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

#ifexist
Esta función toma un string de entrada, interprétao coma un título de páxina, e devolve un de dous valores, dependendo se páxina existe na wiki local ou non.



A función avalía coma verdadeiro se a páxina existe, se contén contido, está visiblemente baleiro (contén meta-datos como ligazóns de categoría ou palabras máxicas, pero ningún contido visible), está baleira, ou é unha redirección. Soamente páxinas que son ligazóns vermellas avalían cara falso, incluíndo se a páxina existía mais foi borrada.



The function evaluates to  for system messages that have been customized, and for special pages 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 tracking category 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 allows an editor [to add information in one template and this information will be visible in several other templates which all have different formatting.]

Estándar
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:



Agrupando resultados
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

Comportamento de comparación
Tal como con, a comparación é feita numericamente se tanto o string de comparación coma o string de caso so proba son numéricas; ou como string sensible a letras maiúsculas doutra forma:





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

Example:



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

Replacing #ifeq
can be used to reduce expansion depth.

For example: is equivalent to
 * (i.e. )
 * (i.e. )

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

→ '''

→ '''

→ '''

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:



With MediaWiki r86805 - Code Review, 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.

Choiando con fusos horarios
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 pagetitle into segments based on slashes, then returns some of those segments as output.



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



Negative values are accepted for both values. Negative values for  effectively 'strips' segments from the end of the string. Negative values for  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

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:



You can use #titleparts as a small "string parser & converter", but consider that it returns the first substring capitalized.




 * If lower case is needed, use lc: function to control output.


 * You can prepend a 'dummy' slash at the beginning of the string to get the correct first substring capitalization (uppercase or lowercase). Use |2 instead of |1 for.

Certain characters that are illegal in a page title will cause #titleparts to not parse the string.
 * → . Non retorna o resultado esperado: {one



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

Choiando strings
Unha extensión está dispoñíbel para traballar con strings. Véxase Extension:StringFunctions.

Substitución
As funcións sintácticas poden ser substituídas engadindose o termo  antes do carácter #;


 * → o código   será engadido no texto wiki se a páxina existir.

Redireccións
Especially   could be handy in redirects to pages including dates, but this does not work.

Elidindo o carácter de barra vertical en táboas
As funcións sintácticas estragarán as sintaxe de táboas wiki e caracteres de barra vertical, tratando tódolas barras verticais coma divisores de parámetros. Para evitar isto, a maior parte wikis crean un modelo    :! cos seus contidos soamente un carácter puro de barra vertical  ou usan a  palabra máxica   que está dispoñible dende a versión MW 1.24. Isto 'esconde' a barra vertical da sintaxe MediaWiki, asegurando que non será considerado ata que despois de todo os modelos e variables sobre unha páxina sexan expandidos. Será entón interpretado coma unha liña de táboa ou divisor de columna. Alternativamente, o código de táboa en HTML puro pode ser utilizado, aínda que isto sexa menos intuitivo e máis propenso de erro.

Pódese tamén escaparse do carácter de barra vertical, para mostralo coma un carácter simple non interpretado, utilizando unha entidade de carácter HTML:.

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.



For preventing trimming then- and else-parts, see m:Template:If. Some people use also &lt; nowiki &gt; &lt; /nowiki &gt; instead of spaces.


 * → foofoo
 * → foofoo

But this method only allows the rendering of one whitespace, since the parser reduce multiple spaces to a single 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

Véxase tamén

 * Help:Parser functions in templates
 * Help:Calculation (to be moved from Meta)
 * on Meta
 * on Meta
 * Help:Magic words
 * Extension:StringFunctions
 * Extension:PhpTags