Help:Extensão:ParserFunctions

This page is a translated version of the page Help:Extension:ParserFunctions and the translation is 57% complete.
Outdated translations are marked like this.

A extensão Extensão:ParserFunctions fornece onze funções adicionais para complementar as "palavras mágicas ", que já estão presentes na MediaWiki. (pode ser configurado para proporcionar análises adicionais de "manipulação de string"; para mais informações consute aqui ). Todas as funções fornecidas pela extensão têm a forma:

{{#functionname: argument 1 | argument 2 | argument 3 ... }}
PD Nota: Ao editar esta página, você concorda em publicar a sua contribuição no âmbito da licença CC0. Veja as páginas de ajuda do domínio público para mais informações.
PD

#expr

Tipo Operadores
Agrupamento (uso de parênteses) ( )
Números 1234.5   e (2.718)   pi (3.142)
operador binário e   unário +,-
Unário not ceil trunc floor abs exp ln sin cos tan acos asin atan
Binário ^
* / div mod
+ -
Arredondamento round
Lógicos = != <> > < >= <=
and
or

Esta função calcula uma expressão matemática e retorna o resultado. Esta função é avaliada em Extensão:Scribunto através da função mw.ext.ParserFunctions.expr.

{{#expr: expressão }}

Os operadores matemáticos estão listados na tabela da direita, por ordem crescente de precedência. Para mais detalhes sobre a função de cada operador, consulte Help:Cálculos. A exatidão e o formato do resultado retornado dependem do sistema operativo do servidor executor da wiki e do formato numérico do idioma do site.

Quando avaliar utilizando álgera booliana, o número zero assume o valor false e qualquer valor diferente de zero, positivo ou negativo, assume o valor true.

{{#expr: 1 and -1 }}1
{{#expr: 1 and 0 }}0
{{#expr: 1 or -1 }}1
{{#expr: -1 or 0 }}1
{{#expr: 0 or 0 }}0

Um parâmetro de entrada vazio retorna um texto vazio. Expressões inválidas retornam uma das várias mensagens de erro, que pode ser capturada com a função #iferror:

{{#expr: }}
{{#expr: 1+ }}Expression error: Missing operand for +.
{{#expr: 1 = }}Expression error: Missing operand for =.
{{#expr: 1 foo 2 }}Expression error: Unrecognized word "foo".

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

{{#expr: +1 }}1
{{#expr: -1 }}-1
{{#expr: + 1 }}1
{{#expr: - 1 }}-1

Note que, se estiver usando a saída de palavras mágicas, você deve formatá-las, para remover vírgulas e traduzir os numerais. Por exemplo: o $numberofusers resulta em $nou-result, onde desejamos $nou-result-raw que pode ser obtido por $numberofusers2. Isto é especialmente importante em algumas línguas, onde números são traduzidos. Por exemplo, no idioma Bengali "$numberofusers3" produz o resultado "$bengali". For example, {{NUMBEROFUSERS}} results in 17 783 732, where we want 17783732, which can be obtained using {{formatnum :{{NUMBEROFUSERS}}|R}}. This is especially important in some languages, where numerals are translated. For example, in Bengali, {{NUMBEROFUSERS}} produces ৩০,০৬১.

{{#expr:{{NUMBEROFUSERS}}+100}} Expression error: Unrecognized punctuation character " ".
{{#expr:{{formatnum:{{NUMBEROFUSERS}}|R}}+100}}17783832
  Atenção: O operador mod retorna resultados errados para alguns valores do segundo argumento:
{{#expr: 123 mod (2^64-1)}}Division by zero. (produz uma string vazia; deveria ser 123)
Se deseja efetuar cálculos baseados em datas (ex. se a data/hora atuais forem posteriores a outra data/hora), primeiro converta o tempo, após 01 de janeiro de 1970, para o número de segundos usando {{#time: xNU }}, em seguida some e subtraia datas como números.

Arredondamento

Rounds arredonda o número do lado esquerdo a um múltiplo de 1/10 elevado a uma potência, com o expoente igual ao valor truncado de um número do lado direito.

Para arredondar para cima ou para baixo, use os operadores unários ceil ou floor respectivamente.

Caso de teste Resultado Método de arredondamento
{{#expr: 1/3 round 5 }} 0.33333 Com o dígito final menor que 5, o arredondamento aparente não é realizado (0.333333… → 0.33333)
{{#expr: 1/6 round 5 }} 0.16667 Com o dígito final maior ou igual a 5, ocorre o arredondado para cima (0.166666… → 0.16667)
{{#expr: 8.99999/9 round 5 }} 1 Mais uma vez, o resultado é arredondado para cima no último dígito, o que resulta no arredondamento adicional (0.999998… → 1.00000 → 1)
{{#expr: 1234.5678 round -2 }} 1200 Arredondado para os 100 mais próximos por causa dos valores negativos, pois os negativos são arredondados para a esquerda do ponto decimal
{{#expr: 1234.5678 round 2 }} 1234.57 Arredondado para o 100 mais próximo, pois os valores positivos são arredondados para a direita do ponto decimal
{{#expr: 1234.5678 round 2.3 }} 1234.57 Decimais no índice de arredondamento não fazem diferença no resultado arredondado
{{#expr: trunc 1234.5678 }} 1234 Parte decimal truncada (cortada)
Arredondamento para o número inteiro mais próximo
{{#expr: 1/3 round 0 }} 0 Baixando para o valor inteiro mais próximo, que é zero
{{#expr: 1/2 round 0 }} 1 Elevado para o número inteiro mais próximo, que é 1
{{#expr: 3/4 round 0 }} 1 Elevado para o número inteiro mais próximo, que é 1
{{#expr: -1/3 round 0 }} -0 Elevado para o número inteiro mais próximo, que é 0
{{#expr: -1/2 round 0 }} -1 Baixado para o inteiro mais próximo, que é negativo
{{#expr: -3/4 round 0 }} -1 Baixado para o inteiro mais próximo, que é negativo
Arredondamento para cima (elevado) ou para baixo (diminuido) com "ceil" e "floor"
{{#expr: ceil(1/3) }} 1 Até o próximo número inteiro "maior", que é 1
{{#expr: floor(1/3) }} 0 Baixando para o próximo inteiro menor, que é zero
{{#expr: ceil(-1/3) }} -0 Até o próximo número inteiro maior, que é igual a zero
{{#expr: floor(-1/3) }} -1 Baixando para o menor inteiro mais próximo, que é negativo
{{#expr: ceil 1/3 }} 0.33333333333333 Não arredondado uma vez que 1 já é um inteiro
  Atenção: Interpretado como (ceil 1)/3, não ceil(1/3) como se poderia esperar

Textos

Expressões somente trabalham com valores numéricos, não fazem comparação de string ou letras/caracteres. #ifeq pode ser usada

{{#expr: "a" = "a" }}Expression error: Unrecognized punctuation character """.
{{#expr: a = a }}Expression error: Unrecognized word "a".
{{#ifeq: a | a | 1 | 0 }}1

#if

Esta função avalia uma seqüência de teste e determina se é ou não é vazio. Uma seqüência de teste que contém apenas espaço em branco é considerado vazio.

{{#if: string de teste | valor se a string de teste não estiver vazia | valor se a string de teste está vazia (ou apenas espaços em branco) }}
{{#if: primeiro parâmetro | segundo parâmetro | terceiro parâmetro }}

Esta função primeiramente testa se o primeiro parâmetro não está vazio. Se o primeiro parâmetro não estiver vazio a função exibe o segundo argumento. Se o primeiro parâmetro estiver vazio ou contiver apenas espaços em branco (espaços, quebras de linha, etc) ele exibe o terceiro argumento.

{{#if: | yes | no}}no
{{#if: string | yes | no}}yes
{{#if:      | yes | no}}no
{{#if:

| yes | no}}
no

A string de teste é sempre interpretada como texto puro, então expressões matemáticas não serão avaliadas: (veja #ifexpr para isso):

{{#if: 1==2 | yes | no }}yes
{{#if: 0 | yes | no }}yes

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

{{#if: foo | yes }} yes
{{#if: | yes }}
{{#if: foo | | no}}

A função pode ser aninhada. Para isso, aninhe a função #if interior em sua forma integral no lugar de um parâmetro da função delimitadora #if. A profundidade até sete níveis de aninhamento é possível, apesar de que pode depender do wiki ou de um limite de memória.

{{#if: string de teste | valor se a string de teste não estiver vazia | {{#if: string de teste | valor se a string de teste não estiver vazia | valor se a string de teste está vazia (ou apenas espaços em branco) }} }}

Você também pode usar um parâmetro como a string de teste em sua declaração #if. Você precisa se certificar que você adicionou o | (símbolo pipe) após o nome da variável. (Assim, se o parâmetro não tiver um valor, ele será avaliado como um texto vazio em vez do texto "{{{1}}}".)

{{#if:{{{1|}}}|Você digitou texto na variável 1|Não há texto na variável 1}}

Para mais exemplos dessa função analisadora, consulte Help:Funções sintáticas em predefinições .

#ifeq

Essa função do analisador compara duas strings, determina se são idênticas e retorna uma das duas strings com base no resultado. Se forem necessárias mais comparações e strings de saída, considere usar #switch.

{{#ifeq: string 1 | string 2 | value if identical | value if different }}

Se ambas as strings são valores numéricos válidos, as strings são comparadas numericamente:

{{#ifeq: 01 | 1 | equal | not equal}}equal
{{#ifeq: 0 | -0 | equal | not equal}}equal
{{#ifeq: 1e3 | 1000 | equal | not equal}}equal
{{#ifeq: {{#expr:10^3}} | 1000 | equal | not equal}}equal

Caso contrário, a comparação é feita como texto; esta comparação é case sensitive:

{{#ifeq: foo | bar | equal | not equal}}not equal
{{#ifeq: foo | Foo | equal | not equal}}not equal
{{#ifeq: "01" | "1" | equal | not equal}}not equal  (comparar a exemplo semelhante anteriormente, sem as aspas)
{{#ifeq: 10^3 | 1000 | equal | not equal}}not equal  (compara com o exemplo acima, com #expr retorna o primeiro número válido)

Como um exemplo prático, dado um modelo existente Template:Timer usado para definir tamanhos de hora: curtos e longos. Este utiliza o parâmetro como a primeira entrada para comparar com o texto "curto", não há convenção para a ordem, mas é mais simples ler se o parâmetro for o primeiro. O código do modelo é definido como:

{{#ifeq: {{{1|}}} | short | 20 | 40 }}

acontecerá o seguinte:

{{timer|short}}20
{{timer|20}}40
{{timer}}40
  Atenção: Quando usado dentro de uma função de analisador, quaisquer tags de analisador e outras funções de analisador devem ser temporariamente substituídas por um código único . Isso afeta as comparações:
{{#ifeq: <nowiki>foo</nowiki> | <nowiki>foo</nowiki> | equal | not equal}}not equal
{{#ifeq: <math>foo</math> | <math>foo</math> | equal | not equal}}not equal
{{#ifeq: {{#tag:math|foo}} | {{#tag:math|foo}} | equal | not equal}}not equal
{{#ifeq: [[foo]] | [[foo]] | equal | not equal}}equal
Se os textos comparados (tipo strings) forem chamadas para a mesma predefinição que contenha essas etiquetas/tags, então o resultado é verdadeira, mas, se forem chamadas para predefinições diferentes com conteúdo idêntico, o resultado é falso.
  Atenção: As comparações literais com "palavras mágicas sobre nomes de páginas " podem falhar dependendo da configuração da página/site. Por exemplo: dependendo do wiki, o {{FULLPAGENAME}} pode capitalizar a primeira letra e substituir todos os sublinhados por espaços.

To work around this, apply the magic word to both parameters:

{{#ifeq: {{FULLPAGENAME: L'Aquila}} | {{FULLPAGENAME}} | equal | not equal}}equal

#iferror

Esta função recebe uma string de entrada e retorna um de dois resultados; a função avalia a true se a string de entrada contém um objeto HTML com class="error", como gerada por outras funções do analisador, tais como #expr, #time e #rel2abs, erros de predefinições, tais como loops e recursões, e outros erros do analisador do tipo failsoft.

{{#iferror: test string | value if error | value if correct }}

Uma ou ambas as strings de retorno podem ser omitidas. Se a string correct is omitida, the string de teste é retornada se não estiver errada. Se a string de erro também é omitida, uma string vazia é retornada com erro:

{{#iferror: {{#expr: 1 + 2 }} | error | correct }}correct
{{#iferror: {{#expr: 1 + X }} | error | correct }}error
{{#iferror: {{#expr: 1 + 2 }} | error }}3
{{#iferror: {{#expr: 1 + X }} | error }}error
{{#iferror: {{#expr: 1 + 2 }} }}3
{{#iferror: {{#expr: 1 + X }} }}
{{#iferror: {{#expr: . }} | error | correct }}correct
{{#iferror: <strong class="error">a</strong> | error | correct }}error

Some errors may cause a tracking category to be added, using {{#iferror:}} will not suppress the addition of the category.

#ifexpr

Esta função avalia uma expressão matemática e retorna uma de duas strings, dependendo do valor booleano do resultado:

{{#ifexpr: expression | value if true | value if false }}

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

Uma expressão de entrada vazia é avaliada como false:

{{#ifexpr: | yes | no}}no

Como mencionado acima, zero é avaliado como false e qualquer valor diferente de zero é avaliado como true, então esta função é equivalente a uma utilização de #ifeq e #expr apenas:

{{#ifeq: {{#expr: expression }} | 0 | value if false | value if true }}

com exceção de uma expressão de entrada vazia ou errada (uma mensagem de erro é tratada como uma string vazia, não é igual a zero, então temos valor se verdadeiro).

{{#ifexpr: = | yes | no }} Expression error: Unexpected = operator.

comparação

{{#ifeq: {{#expr: = }} | 0 | no | yes }} yes

Um ou outro ou ambos os valores de retorno podem ser omitidos; nenhuma saída é dada quando o pacote apropriado é deixado vazio:

{{#ifexpr: 1 > 0 | yes }}yes
{{#ifexpr: 1 < 0 | yes }}
{{#ifexpr: 0 = 0 | yes }} yes
{{#ifexpr: 1 > 0 | | no}}
{{#ifexpr: 1 < 0 | | no}} no
{{#ifexpr: 1 > 0 }}

Boolean operators of equality or inequality operators are supported.

{{#ifexpr: 0 = 0 or 1 = 0 | yes}}yes
{{#ifexpr: 0 = 0 and 1 = 0 | | no}}no
{{#ifexpr: 2 > 0 or 1 < 0 | yes}}yes
{{#ifexpr: 2 > 0 and 1 > 0 | yes | no}}yes
  Atenção: Os resultados das comparações numéricas feitas com #ifexpr nem sempre equivalem àqueles feitos por #ifeq e #switch. These latter two are more accurate than #ifexpr, and so may not return equivalent results.

Consider these comparisons with the final digit changed:

{{#ifeq: 12345678901234567 | 12345678901234568 | equal | not equal}}not equal
{{#switch: 12345678901234567 | 12345678901234568 = equal | not equal}}not equal

Como o PHP usado em #ifeq e #switch compara dois números do tipo inteiro, ele retorna o resultado esperado corretamente. Whereas with #ifexpr and the same numbers:

{{#ifexpr: 12345678901234567 = 12345678901234568 | equal | not equal}}equal

With the different digit, the result of equal is actually incorrect.

Com o dígito diferente na #ifexpr o resultado será incorreto. Pois o MediaWiki converte números das expressões literais em real (tipo float), que para grandes números inteiros é necessário arredondamento.

#ifexist

Esta função recebe uma string de entrada, interpreta-a como um título da página, e retorna um dos dois valores, dependendo ou não se a página existe no wiki local.

{{#ifexist: page title | value if exists | value if doesn't exist }}

A função é avaliada como true, se a página existir, com conteúdo ou em branco (contendo meta-dados, como links de categoria ou palavras mágicas ) ou se for um redirecionamento . Apenas páginas que estão com link em vermelho são avaliadas como false, inclusive se a página existir, mas foi eliminada.

{{#ifexist: Help:Extension:ParserFunctions/pt-br | exists | doesn't exist }}exists
{{#ifexist: XXHelp:Extension:ParserFunctions/pt-brXX | exists | doesn't exist }}doesn't exist

A função é avaliada como verdadeira quando é "mensagens de sistema " personalizadas e "páginas especiais " definidas pelo software.

{{#ifexist: Special:Watchlist | exists | doesn't exist }}exists
{{#ifexist: Special:CheckUser | exists | doesn't exist }}exists (pois a extensão Checkuser está instalada nesta wiki)
{{#ifexist: MediaWiki:Copyright | exists | doesn't exist }}exists (pois MediaWiki:Copyright foi personalizado)

Se uma página verifica um destino usando #ifexist:, então, essa página aparecerá na lista Special:WhatLinksHere para a página de destino. Então, se o código {{#ifexist:Foo}} foi incluído em tempo real nesta página (Help:Extension:ParserFunctions/pt-br), Special:WhatLinksHere/Foo listará Help:Extension:ParserFunctions/pt-br.

Nas wikis que usam um repositório de mídia compartilhada, #ifexist: pode ser usado para verificar se um arquivo foi enviado para o repositório, mas não para a própria wiki:

{{#ifexist: File:Example.png | exists | doesn't exist }}doesn't exist
{{#ifexist: Image:Example.png | exists | doesn't exist }}doesn't exist
{{#ifexist: Media:Example.png | exists | doesn't exist }}exists

Se uma página de descrição do local, foi criado para o arquivo, o resultado é existe para todos os itens acima.

#ifexist: não funciona com links interwiki.

limites de ifexist

#ifexist: é considerada uma "função dispendiosa"; assim um número limitado podem ser usadas em uma página (incluindo funções em predefinições transcluídas). When this limit is exceeded, any further #ifexist: functions automatically return false, whether the target page exists or not, and the page is categorized into Category:Pages with too many expensive parser function calls. O nome da tracking pode variar dependendo do idioma da wiki.

Em alguns casos, é possível fazer o efeito da função com estilo CSS, usando os seletores a.new (selecionar links de páginas que não existentes) ou a:not(.new) (selecionar links de páginas existentes). O número de "Parser Functions" que pode ser usada em uma única página é controlado pela variável $wgExpensiveParserFunctionLimit , que pode ter o limite aumentado no arquivo LocalSettings.php.

ifexist and wanted pages

A page that does not exist and is tested for using #ifexist will end up on the Wanted Pages. See tarefa T14019 for the reason, and w:Template:Linkless exists for a workaround.

#rel2abs

Essa função converte um caminho de arquivo relativo em um caminho absoluto.

{{#rel2abs: path }}
{{#rel2abs: path | base path }}

Na entrada path, a seguinte sintaxe é válida:

  • . → o nível atual
  • .. → suba um nível
  • /foo → desça um nível na subdiretoria /foo

Se o base path não for especificado, o nome completo da página será usado em vez disso:

{{#rel2abs: /quok | Help:Foo/bar/baz }}Help:Foo/bar/baz/quok
{{#rel2abs: ./quok | Help:Foo/bar/baz }}Help:Foo/bar/baz/quok
{{#rel2abs: ../quok | Help:Foo/bar/baz }}Help:Foo/bar/quok
{{#rel2abs: ../. | Help:Foo/bar/baz }}Help:Foo/bar

Sintaxe inválida, como /. ou /./, é ignorada. Desde são permitidos no máximo dois pontos finais consecutivos, sequências como essas podem ser usadas para separar as declarações sucessivas:

{{#rel2abs: ../quok/. | Help:Foo/bar/baz }}Help:Foo/bar/quok
{{#rel2abs: ../../quok | Help:Foo/bar/baz }}Help:Foo/quok
{{#rel2abs: ../../../quok | Help:Foo/bar/baz }}quok
{{#rel2abs: ../../../../quok | Help:Foo/bar/baz }}Error: Invalid depth in path: "Help:Foo/bar/baz/../../../../quok" (tried to access a node above the root node).

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

#switch

Ver também: w:Help:Switch parser function

Essa função compara um valor de entrada contra vários casos de teste, retornando uma string associada, se for encontrada uma correspondência.

{{#switch: comparison string
 | case = result
 | case = result
 | ...
 | case = result
 | default result
}}

Exemplos:

{{#switch: baz | foo = Foo | baz = Baz | Bar }} Baz
{{#switch: foo | foo = Foo | baz = Baz | Bar }} Foo
{{#switch: zzz | foo = Foo | baz = Baz | Bar }} Bar

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

Padrão

O resultado padrão é retornado se nenhuma string case corresponder à string de comparação:

{{#switch: test | foo = Foo | baz = Baz | Bar }} Bar

Nesta sintaxe, o resultado padrão deve ser o último parâmetro e não deve conter um sinal de igual bruto (um sinal de igual sem {{}}). 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.

{{#switch: test | Bar | foo = Foo | baz = Baz }} →
{{#switch: test | foo = Foo | baz = Baz | B=ar }} →
{{#switch: test | test = Foo | baz = Baz | B=ar }} → Foo

Alternativamente, o resultado padrão pode ser declarado explicitamente com uma string case de "#default".

{{#switch: comparison string
 | case = result
 | case = result
 | ...
 | case = result
 | #default = default result
}}

Resultados padrão declarados desta forma podem ser colocados em qualquer lugar dentro da função:

{{#switch: test | foo = Foo | #default = Bar | baz = Baz }} Bar

Se o parâmetro "padrão" for omitido e nenhuma correspondência for feita, nenhum resultado é retornado:

{{#switch: test | foo = Foo | baz = Baz }}

Agrupamento de resultados

É possível ter queda por meio de valores, onde vários strings case retornam a mesma string result. Isso minimiza a duplicação.

{{#switch: comparison string
 | case1 = result1
 | case2 
 | case3 
 | case4 = result234
 | case5 = result5
 | case6 
 | case7 = result67
 | #default = default result
}}

Aqui, os casos 2, 3 e 4 retornam result234; os casos 6 e 7 retornam result67 The "#default = " in the last parameter may be omitted in the above case.

Use with parameters

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 "{{{parameter name}}}". (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 Help:Funções sintáticas em predefinições .)

{{#switch: {{{1}}} | foo = Foo | baz = Baz | Bar }}

In the above case, if {{{1}}} equals foo, the function will return Foo. If it equals baz, the function will return Baz. If the parameter is empty or does not exist, the function will return Bar.

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

{{#switch: {{{1}}} | foo | zoo | roo = Foo | baz = Baz | Bar }}

Here, if {{{1}}} equals foo, zoo or roo, the function will return Foo. If it equals baz, the function will return Baz. If the parameter is empty or does not exist, the function will return Bar.

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.

{{#switch: {{{1}}} | foo = Foo | bar = Bar }}

In this case, the function returns an empty string unless {{{1}}} exists and equals foo or bar, in which case it returns Foo or Bar, respectively.

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

{{#switch: {{{1}}} | foo | zoo | roo = Foo | baz = Baz | }}

If for some reason you decide to set a case as "{{{parameter name}}}", 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 "{{{parameter name}}}" to return the function's default result.

(when {{{1}}} doesn't exist or is empty):
{{#switch: {{{1}}} | {{{1}}} = Foo | baz = Baz | Bar }} Foo
(when {{{1}}} has the value "test"):
{{#switch: {{{1}}} | {{{1}}} = Foo | baz = Baz | Bar }} Bar
(when {{{1}}} has the value "{{{1}}}"):
{{#switch: {{{1}}} | {{{1}}} = Foo | baz = Baz | Bar }} Foo


In this hypothetical case, you would need to add the pipe to the parameter ({{{1|}}}).

Comportamento de comparação

Tal como acontece com #ifeq, a comparação é feita numericamente se tanto a string de comparação e a string case forem números; ou como uma string case-sensitive de outra forma:

{{#switch: 0 + 1 | 1 = one | 2 = two | three}} → three
{{#switch: {{#expr: 0 + 1}} | 1 = one | 2 = two | three}} → one
{{#switch: 02 | +1 = one | +2 = two | three}} → two
{{#switch: 100 | 1e1 = ten | 1e2 = hundred | other}} → hundred
{{#switch: a | a = A | b = B | C}} → A
{{#switch: A | a = A | b = B | C}} → C

Uma string case pode estar vazia:

{{#switch: | = Nothing | foo = Foo | Something }}Nothing

Uma vez que a correspondência for encontrada, cases subsequentes são ignorados:

{{#switch: b | f = Foo | b = Bar | b = Baz | }}Bar
  Atenção: Comparações numéricas com #switch e #ifeq não são equivalentes com comparações em expressões (ver também acima):
{{#switch: 12345678901234567 | 12345678901234568 = A | B}} → B
{{#ifexpr: 12345678901234567 = 12345678901234568 | A | B}} → A


Sinais de igual brutos

Strings "case" não pode conter o sinal de igual (=). Para contornar isso, crie uma predefinição {{=}} contendo um sinal de igual simples: =: use =, ou faça a substituição com o html &#61;.

Exemplo:

You type You get
{{#switch: 1=2
 | 1=2 = raw
 | 1<nowiki>=</nowiki>2 = nowiki
 | 1{{=}}2 = template
 | default
}}
template
{{#switch: 1=2
 | 1&#61;2 = html
 | default
}}
html
Para um exemplo real simples da utilização desta função, verifique [$enwp-nba-color Template:NBA color]. Dois exemplos complexos podem ser encontrados em $tpl-ext e w:Template:BOTREQ.


Substituição de #ifeq

#switch pode ser usado para reduzir a profundidade de expansão.

Por exemplo:

  • {{#switch:{{{1}}} |condition1=branch1 |condition2=branch2 |condition3=branch3 |branch4}}

é equivalente a

  • {{#ifeq:{{{1}}}|condition1 |branch1 |{{#ifeq:{{{1}}}|condition2 |branch2 |{{#ifeq:{{{1}}}|condition3 |branch3 |branch4}}}}}}

i.e. deep nesting, linear:

{{#ifeq:{{{1}}}|condition1
  |<!--then-->branch1
  |<!--else-->{{#ifeq:{{{1}}}|condition2
                |<!--then-->branch2
                |<!--else-->{{#ifeq:{{{1}}}|condition3
                              |<!--then-->branch3
                              |<!--else-->branch4}}}}}}

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:

{{#ifeq:{{{1}}}|condition1
 |<!--then-->branch1t{{
  #ifeq:{{{1}}}|condition2
   |<!--then-->branch1t2t{{#ifeq:{{{1}}}|condition4|<!--then-->branch1t2t4t|<!--else-->branch1t2t4e}}
   |<!--else-->branch1t2e{{#ifeq:{{{1}}}|condition5|<!--then-->branch1t2e5t|<!--else-->branch1t2e5e}}
  }}
 |<!--else-->branch1e{{#ifeq:{{{1}}}|condition3
   |<!--then-->branch1e3t{{#ifeq:{{{1}}}|condition6|branch1e3t6t|branch1e3t6e}}
   |<!--else-->branch1e3e{{
    #ifeq:{{{1}}}|condition7
     |branch1e3e7t
     |branch1e3e7t
    }}
  }}
}}

#time

Esta parser function pega uma data e/ou uma hora (no calendário Gregoriano) e formata-o de acordo com a sintaxe fornecida. Um objeto de data/hora pode ser especificado; o padrão é o valor da palavra mágica {{CURRENTTIMESTAMP}} – isto é, a hora em que a página foi renderizada dentro do HTML.

{{#time: format string }}
{{#time: format string | date/time object }}
{{#time: format string | date/time object | language code }}
{{#time: format string | date/time object | language code | local }}

A lista de códigos de formatação válidos é apresentada na tabela à direita. Qualquer caractere na string de formatação que não é reconhecido, é passado inalterado; isto aplica-se também aos espaços em branco (o sistema não precisa deles para interpretar os códigos). Há também duas maneiras de escapar os caracteres da string de formatação:

  1. Uma barra invertida seguido por um caractere de formatação é interpretada como um único caractere literal
  2. Caracteres entre aspas duplas são considerados caracteres literais, e as aspas são removidas.

Além disso, o dígrafo xx é interpretada como um literal simples "x". 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:

  1. A backslash followed by a formatting character is interpreted as a single literal character
  1. Characters enclosed in double quotes are considered literal characters, and the quotes are removed.

In addition, the digraph xx is interpreted as a single literal "x".

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

{{#time: Y-m-d }}2023-06-02
{{#time: [[Y]] m d }}2023 06 02
{{#time: [[Y (year)]] }}2023 (23UTCamFri, 02 Jun 2023 06:32:47 +0000)
{{#time: [[Y "(year)"]] }}2023 (year)
{{#time: i's" }}32'47"

O objeto data/hora pode ser em qualquer formato aceito na função strtotime() do PHP. Absolute (e.g. 20 December 2000), relative (e.g. +20 hours), and combined times (e.g. 30 July +1 year) are accepted.

{{#time: r|now}}Fri, 02 Jun 2023 06:32:47 +0000
{{#time: r|+2 hours}}Fri, 02 Jun 2023 08:32:47 +0000
{{#time: r|now + 2 hours}}Fri, 02 Jun 2023 08:32:47 +0000
{{#time: r|20 December 2000}}Wed, 20 Dec 2000 00:00:00 +0000
{{#time: r|December 20, 2000}}Wed, 20 Dec 2000 00:00:00 +0000
{{#time: r|2000-12-20}}Wed, 20 Dec 2000 00:00:00 +0000
{{#time: r|2000 December 20}}Error: Invalid time.

O código de idioma em ISO 639-3 (?) permite que a string seja exibida no idioma escolhido

{{#time:d F Y|1988-02-28|nl}}28 februari 1988
{{#time:l|now|uk}}п'ятниця
{{#time:d xg Y|20 June 2010|pl}}20 czerwca 2010

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

Please note that, if the variable $wgLocaltimezone is set to UTC, there is no difference in the output when local is set to true or false.

See the following examples for details:

{{#time: Y F d H:i:s|now|it|0}}2023 giugno 02 06:32:47
{{#time: Y F d H:i:s|now|it|1}}2023 giugno 02 06:32:47
{{#time: Y F d H:i:s|+2 hours||0}}2023 junho 02 08:32:47
{{#time: Y F d H:i:s|+2 hours||1}}2023 junho 02 08:32:47
{{#time:c|2019-05-16T17:05:43+02:00|it}}2019-05-16T15:05:43+00:00
{{#time:c|2019-05-16T17:05:43+02:00|it|0}}2019-05-16T15:05:43+00:00
{{#time:c|2019-05-16T17:05:43+02:00|it|true}}2019-05-16T15:05:43+00:00

Se você já calculou um timestamp Unix, você pode usá-lo em cálculos de data, pré-pendendo um símbolo @.

{{#time: U | now }}1685687567
{{#time: r | @1685687567 }}Fri, 02 Jun 2023 06:32:47 +0000
  Atenção: Sem o prefixo @ depois da marca de tempo, o resultado será um erro ou um valor inexperado:
{{#time: r | 1970-01-01 00:16:39 }}Thu, 01 Jan 1970 00:16:39 +0000
{{#time: U | 1970-01-01 00:16:39 }}999
{{#time: r | @999 }}Thu, 01 Jan 1970 00:16:39 +0000 (correto)
{{#time: r | 999 }}Error: Invalid time. (formato de ano não suportado)
{{#time: r | 1970-01-01 00:16:40 }}Thu, 01 Jan 1970 00:16:40 +0000
{{#time: U | 1970-01-01 00:16:40 }}1000
{{#time: r | @1000 }}Thu, 01 Jan 1970 00:16:40 +0000 (correto)
{{#time: r | 1000 }}Mon, 02 Jun 1000 00:00:00 +0000 (interpreted as a year with current month and day of the month)
{{#time: r | 1970-01-01 02:46:39 }}Thu, 01 Jan 1970 02:46:39 +0000
{{#time: U | 1970-01-01 02:46:39 }}9999
{{#time: r | @9999 }}Thu, 01 Jan 1970 02:46:39 +0000 (coreto)
{{#time: r | 9999 }}Wed, 02 Jun 9999 00:00:00 +0000 (interpreted as a year with current month and day of the month)
{{#time: r | 1970-01-01 02:46:40 }}Thu, 01 Jan 1970 02:46:40 +0000
{{#time: U | 1970-01-01 02:46:40 }}10000
{{#time: r | @10000 }}Thu, 01 Jan 1970 02:46:40 +0000 (coreto)
{{#time: r | 10000 }}Error: Invalid time. (unsupported year format)
  Atenção: O intervalo de entrada aceitável é de 1º. de Janeiro de 0111 → 31 de Dezembro de 9999. Para os anos de 100 a 110, a saída é inconsistente, Y e os anos bissextos são como os anos 100-110, r, D, l e U são como interpretar esses anos como 2000-2010.
{{#time: d F Y | 29 Feb 0100 }}01 março 0100
(correto, sem ano bissexto), porém
{{#time: r | 29 Feb 0100 }}Mon, 01 Mar 0100 00:00:00 +0000 (errado, mesmo que 100 seja interpretado como 2000, porque esse é um ano bissexto)
{{#time: d F Y | 15 April 10000 }}Error: Invalid time.
{{#time: r | 10000-4-15 }}Sat, 15 Apr 2000 10:00:00 +0000

Os números de ano 0-99 são interpretados como 2000-2069 e 1970-1999, exceto quando escrito em formato de 4 dígitos com zeros à frente:

{{#time: d F Y | 1 Jan 6 }}01 janeiro 2006
{{#time: d F Y | 1 Jan 06 }}01 janeiro 2006
{{#time: d F Y | 1 Jan 006 }}01 janeiro 2006
{{#time: d F Y | 1 Jan 0006 }}01 janeiro 0006 (4-digit format)
O dia da semana é fornecido para os anos 100-110 e a partir de 1753, para os anos 111-1752 a saída à direita exibe "Unknown" e a saída à esquerda "<>". Como consequencia, a saída à direita não é aceita como entrada para esses anos.

Datas absolutas totais ou parciais podem ser especificadas; a função irá "preencher" as partes da data que não forem especificadas usando os valores 'atuais:

{{#time: Y | January 1 }}2023
  Atenção: O recurso de preenchimento não é consistente; algumas partes são preenchidas com os valores atuais, outras não:
{{#time: Y m d H:i:s | June }}2023 06 02 00:00:00 Fornece o início do dia, porém o dia atual do mês e do ano em curso.
{{#time: Y m d H:i:s | 2003 }}2003 06 02 00:00:00 Fornece o início do dia, mas o dia atual do ano.

There's exception case of the filled day:

{{#time: Y m d H:i:s | June 2003 }}2003 06 01 00:00:00 Gives the start of the day and the start of the month.

Um número de quatro dígitos é sempre interpretado como um ano, nunca como horas e minutos:[1]

{{#time: Y m d H:i:s | 1959 }}1959 06 02 00:00:00

Um número de seis dígitos é interpretado como horas, minutos e segundos, se possível, mas de outra forma, como um erro (não, por exemplo, um ano e mês):

{{#time: Y m d H:i:s | 195909 }}2023 06 02 19:59:09 A entrada é tratada como uma hora em vez de um código de ano + mês.
{{#time: Y m d H:i:s | 196009 }}Error: Invalid time. Embora 19:60:09 não é uma hora válida, 196009 não é interpretado como setembro de 1960.

A função executa uma certa quantidade de matemática de data:

{{#time: d F Y | January 0 2008 }}31 dezembro 2007
{{#time: d F | January 32 }}Error: Invalid time.
{{#time: d F | February 29 2008 }}29 fevereiro
{{#time: d F | February 29 2007 }}01 março
{{#time:Y-F|now -1 months}}2023-maio

O comprimento total das strings de formato das chamadas de #time se limita a 6000 caracteres[2].

Questão do fuso horário

Existe um bug nesta parser function #time (mais especificamente em PHP DateTime) que não permite a passagem de não-inteiros como deslocamentos de fuso horário relativos. Este problema não se aplica quando se usa um fuso horário exato, como EDT. Por exemplo:

  • {{#time:g:i A | -4 hours }} → 2:32 AM

Entretanto, a Índia está a +5.5 horas do UTC, e, assim, usar seu fuso horário não permitirá normalmente o cálculo correto de um deslocamento de fuso horário relativo. Veja o que acontece:

  • {{#time:g:i A | +5.5 hours }} → 6:32 AM

Para contornar este problema, basta converter o tempo em minutos ou segundos, assim:

  • {{#time:g:i A | +330 minutes }} → 12:02 PM
  • {{#time:g:i A | +19800 seconds }} → 12:02 PM

(Tim Starling, o desenvolvedor desta função, forneceu a sintaxe exata para esta solução.)

#timel

Esta função é idêntica à {{#time: ... }}, quando o parâmetro local é definido como true, portanto ela sempre usa o horário local da wiki (como definido em $wgLocaltimezone ).

Syntax of the function is:

{{#timel: format string }}
{{#timel: format string | date/time object }}
{{#timel: format string | date/time object | language code }}
Please note that, if the variable $wgLocaltimezone is set to UTC, there is no difference in the output when local is set to true or false
 
Example of the use of #time and #timel parser functions from a server where the timezone is not UTC

For instance, see the following examples:

{{#time:c|now|it}}2023-06-02T06:32:47+00:00
{{#time:c|now|it|0}}2023-06-02T06:32:47+00:00
{{#time:c|now|it|1}}2023-06-02T06:32:47+00:00
{{#timel:c|now|it}}2023-06-02T06:32:47+00:00
 
Warning Example from https://no.wikipedia.org/wiki/Maldiskusjon:Sommertid
  Atenção:

Be aware that U for both time and timel will return the same number of seconds since 1970-01-01 00:00:00 UTC on Wikipedias with different timezones than UTC (formerly known as GMT)

U Unix time. Seconds since January 1 1970 00:00:00 GMT.
Z Deslocamento em segundos do fuso horário.
{{#time: U}}1685687567
{{#timel: U}}1685687567
{{#time: Z}}0
{{#timel: Z}}0

#titleparts

Esta função separa um título de página em segmentos baseados em barras, em seguida, retorna alguns desses segmentos como saída.

{{#titleparts: nome da página | número de segmentos no resultado | primeiro segmento do resultado }}

Se o parâmetro número de segmentos não for especificado, o padrão é "0", que retorna todos os segmentos do primeiro segmento (incluído). Se o parâmetro primeiro segmento não for especificado ou for "0", o padrão é "1":

{{#titleparts: Talk:Foo/bar/baz/quok }}Talk:Foo/bar/baz/quok
{{#titleparts: Talk:Foo/bar/baz/quok | 1 }}Talk:Foo See also {{ROOTPAGENAME }}.
{{#titleparts: Talk:Foo/bar/baz/quok | 2 }}Talk:Foo/bar
{{#titleparts: Talk:Foo/bar/baz/quok | 2 | 2 }}bar/baz
{{#titleparts: Talk:Foo/bar/baz/quok | | 2 }}bar/baz/quok
{{#titleparts: Talk:Foo/bar/baz/quok | | 5 }}

Valores negativos são aceitos para ambos os valores. Valores negativos para o número de segmentos para retornar efetivamente efetivamente 'faixas' segmentos do final da seqüência de caracteres. Valores negativos para o primeiro segmento para retornar traduz-se para "começar com este segmento contando da direita":

{{#titleparts: Talk:Foo/bar/baz/quok | -1 }}Talk:Foo/bar/baz Retira um segmento a partir do final da string. Ver também {{BASEPAGENAME}}.
{{#titleparts: Talk:Foo/bar/baz/quok | -4 }} Retira todos os quatro segmentos a partir do final da string
{{#titleparts: Talk:Foo/bar/baz/quok | -5 }} Retira 5 segmentos a partir do final da string (mais do que existe)
{{#titleparts: Talk:Foo/bar/baz/quok | | -1 }} quok Retorna o último segmento. Ver também {{SUBPAGENAME}}.
{{#titleparts: Talk:Foo/bar/baz/quok | -1 | 2 }} bar/baz Retira um segmento a partir do final da string, em seguida, retorna o segundo segmento e mais além
{{#titleparts: Talk:Foo/bar/baz/quok | -1 | -2 }} baz Inicia a cópia no penúltimo elemento; retira um segmento a partir do final da 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).

Por exemplo, todas as ocorrência de &quot;, &#34;, ou &#x22; no "nome da página" serão substituida por ".
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.

Some magic keywords or parser functions of MediaWiki (such as {{PAGENAME }} and similar) are known to return strings that are needlessly HTML-encoded, even if their own input parameter was not HTML-encoded:

The titleparts parser function can then be used as a workaround, to convert these returned strings so that they can be processed correctly by some other parser functions also taking a page name in parameter (such as {{PAGESINCAT: }} but which are still not working properly with HTML-encoded input strings.

For example, if the current page is Category:Côte-d'Or, then:

  • {{#ifeq: {{FULLPAGENAME}} | Category:Côte-d'Or | 1 | 0 }}, and {{#ifeq: {{FULLPAGENAME}} | Category:Côte-d&apos;Or | 1 | 0 }} are both returning 1; (the #ifeq parser function does perform the HTML-decoding of its input parameters).
  • {{#switch: {{FULLPAGENAME}} | Category:Côte-d'Or = 1 | #default = 0 }}, and {{#switch: {{FULLPAGENAME}} | Category:Côte-d&apos;Or = 1 | #default = 0 }} are both returning 1; (the #switch parser function does perform the HTML-decoding of its input parameters).
  • {{#ifexist: {{FULLPAGENAME}} | 1 | 0 }}, {{#ifexist: Category:Côte-d'Or | 1 | 0 }}, or even {{#ifexist: Category:Côte-d&apos;Or | 1 | 0 }} will all return 1 if that category page exists (the #ifexist parser function does perform the HTML-decoding of its input parameters);
  • {{PAGESINCAT: Côte-d'Or }} will return a non-zero number, if that category contains pages or subcategories, but:
  • {{PAGESINCAT: {{CURRENTPAGENAME}} }}, may still unconditionally return 0, just like:
  • {{PAGESINCAT: {{PAGENAME:Category:Côte-d'Or}} }}
  • {{PAGESINCAT: {{PAGENAME:Category:Côte-d&apos;Or}} }}

The reason of this unexpected behavior is that, with the current versions of MediaWiki, there are two caveats:

  • {{FULLPAGENAME}}, or even {{FULLPAGENAME:Côte-d'Or}} may return the actually HTML-encoded string Category:Côte-d&apos;Or and not the expected Category:Côte-d'Or, and that:
  • {{PAGESINCAT: Côte-d&apos;Or }} unconditionally returns 0 (the PAGESINCAT magic keyword does not perform any HTML-decoding of its input parameter).

The simple workaround using titleparts (which will continue to work if the two caveats are fixed in a later version of MediaWiki) is:

  • {{PAGESINCAT: {{#titleparts: {{CURRENTPAGENAME}} }} }}
  • {{PAGESINCAT: {{#titleparts: {{PAGENAME:Category:Côte-d'Or}} }} }}
  • {{PAGESINCAT: {{#titleparts: {{PAGENAME:Category:Côte-d&apos;Or}} }} }}, that all return the actual number of pages in the same category.

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:
    {{#titleparts: Talk:Foo/bah_boo|1|2}}bah boo Not bah_boo, despite the underscore in the original.
  2. A string é dividida em um máximo de 25 vezes; outras barras são ignoradas e o elemento 25 irá conter o resto da string. A string é também limitada a 255 caracteres, então ela é tratada como um título de página:
    {{#titleparts: a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/aa/bb/cc/dd/ee | 1 | 25 }}y/z/aa/bb/cc/dd/ee
    Se por qualquer motivo você precisava empurrar esta função ao seu limite, embora muito improvável, é possível contornar o limite de divisão de 25 pela chamada da função de aninhamento:
    {{#titleparts: {{#titleparts: a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/w/x/y/z/aa/bb/cc/dd/ee| 1 | 25 }} | 1 | 2}}z
  3. 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).
    {{#titleparts: talk:a/b/c }}Talk:A/b/c
  Atenção: Você pode usar #titleparts como um simples "analisador e conversor de strings", mas saiba que ela retorna a primeira substring capitalizada.
{{#titleparts: one/two/three/four|1|1 }}One
{{#titleparts: one/two/three/four|1|2 }}two

Se forem necessárias minúsculas, use lc: função para controlar a saída:

{{lc: {{#titleparts: one/two/three/four|1|1 }} }}one
  • Você pode preceder uma barra 'simulada' no início da string para obter a capitalização correta da primeira substring (maiúscula ou minúscula). Use 2 em vez de 1 para retorno do primeiro segmento:
{{#titleparts: /one/two/three/four|1|2 }}one
{{#titleparts: /One/two/three/four|1|2 }}One
  Atenção: Certos caracteres que são ilegais em um título de página farão com que #titleparts não analise a string.
{{#titleparts: {one/two} | 1 | 1 }}{one/two}. Não produz o esperado: {one
{{#titleparts: [[page]]/123 | 1 | 2 }}page/123. 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.
  Atenção:

If any part of the title is just "." or "..", #titleparts will not parse the string:

{{#titleparts: one/./three | 1 | 1 }}one/./three. The whole string is returned. It does not produce the expected: one
  Atenção: Esta função não é degradada normalmente se a entrada exceder 255 bytes em UTF-8. Se a string de entrada tiver 256 bytes ou mais, toda a string será retornada.


StringFunctions

All of these functions (len, pos, rpos, sub, replace, explode) are integrated from the StringFunctions extension, but are only available if an administrator sets $wgPFEnableStringFunctions = true; in LocalSettings.php.

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

  1. Some parameters of these functions are limited through global settings to prevent abuse.
See section Limits hereafter.
  1. For functions that are case sensitive, you may use the magic word {{lc:string}} as a workaround in some cases.
  1. To determine whether a MediaWiki server enables these functions, check the list of supported Extended parser functions in Special:Version.
  1. String length is limited by $wgPFStringLengthLimit variable, default to 1000.

#len

The #len parser function was merged from the StringFunctions extension as of version 1.2.0.

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

{{#len:string}}

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.

  • This function is safe with UTF-8 multibyte characters.
Exemplo:
    • {{#len:Žmržlina}}8
  • Leading and trailing spaces or newlines are not counted, but intermediate spaces and newlines are taken into account.
Exemplos:
    • {{#len:Icecream }}8
    • {{#len: a   b }}5 - 3 spaces between 2 characters
  • Characters given by reference are not converted, but counted according to their source form.
    • {{#len:&nbsp;}}6 - named characters references
    • {{#len:&#32;}}5 - numeric characters references, not ignored despite it designates a space here.
  • Tags such as ‎<nowiki> and other tag extensions will always have a length of zero, since their content is hidden from the parser.
Exemplo:
    • {{#len:<nowiki>This is a </nowiki>test}}4

#pos

The #pos parser function was merged from the StringFunctions extension as of version 1.2.0.

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

{{#pos:string|search term|offset}}

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.

  • This function is case sensitive.
  • This function is safe with UTF-8 multibyte characters.
Exemplo: {{#pos:Žmržlina|žlina}} returns 3.
  • As with #len, ‎<nowiki> and other tag extensions are treated as having a length of 1 for the purposes of character position.
Exemplo: {{#pos:<nowiki>This is a </nowiki>test|test}} returns 1.

#rpos

The #rpos parser function was merged from the StringFunctions extension as of version 1.2.0.

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

{{#rpos:string|search term}}

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.

When using this to search for the last delimiter, add +1 to the result to retrieve position after the last delimiter. This also works when the delimiter is not found, because "-1 + 1" is zero, which is the beginning of the given value.
  • This function is case sensitive.
  • This function is safe with UTF-8 multibyte characters.
Exemplo: {{#rpos:Žmržlina|lina}} returns 4.
  • As with #len, ‎<nowiki> and other tag extensions are treated as having a length of 1 for the purposes of character position.
Exemplo: {{#rpos:<nowiki>This is a </nowiki>test|test}} returns 1.

#sub

The #sub parser function was merged from the StringFunctions extension as of version 1.2.0.

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

{{#sub:string|start|length}}

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

Exemplo: {{#sub:Icecream|3}} returns cream.

{{#sub:Icecream|0|3}} returns Ice.

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

Exemplo: {{#sub:Icecream|-3}} returns eam.

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

Exemplo: {{#sub:Icecream|3|3}} returns cre.

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

Exemplo: {{#sub:Icecream|3|-3}} returns cr.

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.

Exemplo: {{#sub:Icecream|-3|2}} returns ea.

  • If the length parameter is zero, it is not used for truncation at all.
    • Exemplo: {{#sub:Icecream|3|0}} returns cream. {{#sub:Icecream|0|3}} returns Ice.
  • If start denotes a position beyond the truncation from the end by negative length parameter, an empty string will be returned.
    • Exemplo: {{#sub:Icecream|3|-6}} returns an empty string.
  • This function is safe with UTF-8 multibyte characters.
Exemplo: {{#sub:Žmržlina|3}} returns žlina.
  • As with #len, ‎<nowiki> and other tag extensions are treated as having a length of 1 for the purposes of character position.
Exemplo: {{#sub:<nowiki>This is a </nowiki>test|1}} returns test.

#count

The #count parser function was added to the StringFunctions extension as of version 1.2.0.

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

{{#count:string|substring}}

#replace

The #replace parser function was merged from the StringFunctions extension as of version 1.2.0.

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

{{#replace:string|search term|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.

  • This function is case-sensitive.
  • Even if the replacement term is a space, an empty string is used.
This is a side-effect of the MediaWiki parser. To use a space as the replacement term, put it in nowiki tags.
    • Exemplo: {{#replace:My_little_home_page|_|<nowiki> </nowiki>}} returns My little home page.
    • If this doesn't work, try {{#replace:My_little_home_page|_|<nowiki/> <nowiki/>}} with two self-closing tags.
    • Note that this is the only acceptable use of nowiki in the replacement term, as otherwise nowiki could be used to bypass $wgStringFunctionsLimitReplace, injecting an arbitrarily large number of characters into the output.
For this reason, all occurrences of ‎<nowiki> or any other tag extension within the replacement term are replaced with spaces.
  • This function is safe with UTF-8 multibyte characters.
Exemplo: {{#replace:Žmržlina|ž|z}} returns Žmrzlina.
  • If multiple items in a single text string need to be replaced, one could also consider Extension:ReplaceSet .
It adds a parser function for a sequence of replacements.
Case-insensitive replace

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. {{lc:your_string_here}}) For example, if you want to remove the word "Category:" from the string regardless of its case, you may type:

{{#replace:{{lc:{{{1}}}}}|category:|}}

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 parser function was merged from the StringFunctions extension as of version 1.2.0.

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

{{#explode:string|delimiter|position|limit}}

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

  • {{#explode:And if you tolerate this| |2}} returns you
  • {{#explode:String/Functions/Code|/|-1}} returns Code
  • {{#explode:Split%By%Percentage%Signs|%|2}} returns Percentage
  • {{#explode:And if you tolerate this thing and expect no more| |2|3}} returns you tolerate this thing and expect no more

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

  • This function is case sensitive.
  • The maximum allowed length of the delimiter is limited through $wgStringFunctionsLimitSearch global setting.
  • This function is safe with UTF-8 multibyte characters. Example: {{#explode:Žmržlina|ž|1}} returns lina.

#urldecode

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

{{#urldecode:value}}

Notes:

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

Limits

This module defines three global settings:

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.

Pontos gerais

Substituição

Funções do analisador podem ser substituídas prefixando o caractere hash (#) com subst::

{{subst:#ifexist: Help:Extension:ParserFunctions/pt-br | [[Help:Extension:ParserFunctions/pt-br]] | Help:Extension:ParserFunctions/pt-br }} → o código [[Help:Extension:ParserFunctions/pt-br]] será inserida no wikitexto desde que a página Help:Extension:ParserFunctions/pt-br exista.
  Atenção: Os resultados das funções do analisador substituídas são indefinidos se as expressões contiverem código volátil não substituído como variáveis ou outras funções do analisador. Para obter resultados consistentes, todo o código volátil na expressão a ser avaliada deve ser substituído. Consulte Help:Substitution.

Substitution does not work within ‎<ref>‎</ref> ; you can use {{subst:#tag:ref|}} for this purpose.

Redirecionamentos

Especially {{#time:…|now-…}} could be handy in redirects to pages including dates, but this does not work.

Escaping pipe characters in tables

Parser functions will mangle wikitable syntax and pipe characters (|), treating all the raw pipe characters as parameter dividers. To avoid this, most wikis used a template Template:! with its contents only a raw pipe character (|), since MW 1.24 a {{!}} magic word 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: &#124; .

Descrição Você digita O resultado é
Escaping pipe character as table row/column separator
{{!}}
|
Escaping pipe character as a plain character
&#124;
|


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.

{{#ifeq: foo           |           foo | equal | not equal }}equal
{{#ifeq: "foo          " | "          foo" | equal | not equal }}not equal

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

foo{{#if:|| bar }}foofoobarfoo
foo{{#if:||<nowiki /> bar <nowiki />}}foofoo bar foo

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.

<span style="white-space: pre;">foo{{#if:||<nowiki/>      bar      <nowiki/>}}foo</span>
foo bar foo

In this example, the white-space: pre 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 &#32; (breakable space) or &nbsp; (non-breakable space), since they are not modified by the software:

<span style="white-space: pre;">foo{{#if:||&#32;&#32;&#32;bar&#32;&#32;&#32;}}foo</span>foo bar foo
foo{{#if:||&nbsp;&nbsp;&nbsp;bar&nbsp;&nbsp;&nbsp;}}foofoo   bar   foo

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:

foo{{1x|content= bar}}foofoobarfoo
foo{{1x|1= bar}}foofoobarfoo
foo{{1x| bar }}foofoo bar foo

Ver também


Referências

  1. Antes de r86805 em 2011, esse não era o caso.
  2. ParserFunctions_body.php em phabricator.wikimedia.org