Movatterモバイル変換


[0]ホーム

URL:


Jump to content
MediaWiki
Search

Axuda:Extensión:ParserFunctions

From mediawiki.org
This page is atranslated version of the pageHelp:Extension:ParserFunctions and the translation is 51% complete.
Outdated translations are marked like this.
Languages:
PDNota: Ao editar esta páxina, acepta liberar a súa contribución baixo a licenzaCC0. Consulte aspáxinas de axuda sobre o dominio público para obter máis información.PD

A extensiónParserFunctions fornece once funcións sintácticas adicionais para estender as "palabras máxicas", que xa forman parte de MediaWiki.(Itmay be configured to provide additional parser functions for string handling; these string functions are documentedelsewhere.)Tódalas funcións sintácticas definidas nesta extensión asumen o seguinte paradigma:

{{#nomedafunción:parámetro 1 |parámetro 2 |parámetro 3 ... }}

#expr

Fora morein-depth manual on the finer points of how the expression evaluator works, including some additional operators not covered here, see:Manual:Expr parser function syntax.
TipoOperadores
Agrupación (parénteses)( )
Números1234.5  e (2.718)  pi (3.142)
Operador binarioe   unario+,-
Unariosnot ceil trunc floor abs exp ln sin cos tan acos asin atan sqrt
Binarios^
* / div mod fmod
+ -
Arredondamentoround
Lóxicos= != <> > < >= <=
and
or

Esta función calcula a expresión matemática e devolve o seu resultado.This function is also available inScribunto via themw.ext.ParserFunctions.expr function.

{{#expr:expresión }}

Basic example

{{#expr: 1 + 1}}2

Os operadores dispoñibles son clasificados á dereita, en orde de precedencia. Véxase [[Manual:Expr parser function syntax|Axuda:Cálculo]] 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.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.

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

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

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

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

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 $numberofusers resulta dentro $nou-result, na que se quer $nou-result-raw, cal pode ser obtido utilizando $numberofusers2. Isto é especialmente importante nalgunhas linguas, nas que os números son traducidos. Por exemplo, en bengalí, $numberofusers3 produce $bengali.For example, {{NUMBEROFUSERS}} results in 18.137.919, where we want 18137919, 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}} 118.137
{{#expr:{{formatnum:{{NUMBEROFUSERS}}|R}}+100}}18138019
WarningWarning:O operadormod devolve resultados equivocados para algúns valores do segundo parámetro:
{{#expr: 123 mod (2^64-1)}}Division by zero. (retorna un valor baleiro de string; cando debería devolver 123)
Se o desiderátum for facer cálculos baseados en datas (ex. test se a data e hora actual está despois dalgunha outra data e hora), primeiro, débese converter a hora para contar os segundos despois de 1 de xaneiro de 1970 utilizándose {{#time: xNU }}, entón pódese simplemente sumar e subtraer datas coma números.

Arredondamento

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ébese usar os operadores unariosceil oufloor, respectivamente.

Caso de testResultadoMedio de arredondamento
{{#expr: 1/3 round 5 }}0.33333Se o díxito final for < 5, ningún arredondamento aparente acontece (0.333333… → 0.33333)
{{#expr: 1/6 round 5 }}0.16667Se o díxito final é >= 5, redondease cara arriba (0.166666… → 0.16667)
{{#expr: 8.99999/9 round 5 }}1Outra vez, o resultado é redondeado no último díxito, que sucede nun redondeado adicional (0.999998… → 1.00000 → 1)
{{#expr: 1234.5678round -2 }}1200Redondeado cara máis preto de 100 porque valores negativos redondéanse á esquerda do punto decimal
{{#expr: 1234.5678round 2 }}1234.57Redondeado cara o cento máis preto, porque valores positivos redodéanse á dereita do punto decimal
{{#expr: 1234.5678 round 2.3 }}1234.57Os decimais no índice redondeado non significan ningunha diferenza no resultado redondeado
{{#expr:trunc 1234.5678 }}1234Porción decimal truncada (cortada)
Redondeando ó enteiro máis preto
{{#expr: 1/3round 0 }}0Reducido cara o enteiro "máis preto", que é cero
{{#expr: 1/2round 0 }}1Aumentado cara o enteiro máis preto, que é un
{{#expr: 3/4round 0 }}1Aumentado cara o enteiro máis preto, que é un
{{#expr: -1/3round 0 }}-0Aumentado cara o enteiro máis preto, que é cero
{{#expr: -1/2round 0 }}-1Reducido cara o enteiro máis preto, que é un negativo
{{#expr: -3/4round 0 }}-1Reducido cara o enteiro máis preto, que é un negativo
Redondeamento cara arriba ou baixo con "ceil" e "floor"
{{#expr:ceil(1/3) }}1Aumentado cara o próximo enteiro "meirande", que é un
{{#expr:floor(1/3) }}0Reducido cara o próximo entero "máis pequeno", que é cero
{{#expr:ceil(-1/3) }}-0Aumentado cara o próximo enteiro meirande, que é cero
{{#expr:floor(-1/3) }}-1Reducido cara o próximo entero máis pequeno, que é un negativo
{{#expr:ceil 1/3 }}0.33333333333333Non se redondea porque 1 xa é enteiro
WarningWarning:Interpretado coma(ceil 1)/3 e non comaceil(1/3), como se podería esperar
Rounding large numbers
{{#expr: 1e-92 round 400 }}1.0E-92Rounding to a very large number leads to infinity.Hence, the original value without the infinity is given as the answer.
{{#expr: 1e108 round 200 }}1.0E+108Same as above.

Strings

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

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

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

{{#if: string de test| retorno se string de test é non baleiro| retorno se string de test é baleiro (ou contén soamente espazos en branco)}}
{{#if: primeiro parámetro| segundo parámetro| terceiro parámetro}}

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.

{{#if:| yes| no}}no
{{#if: string| yes| no}}yes
{{#if:&nbsp;&nbsp;&nbsp;&nbsp;| yes| no}}yes
{{#if:| yes| no}}no

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

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

O último parámetro (false) pode omitirse:

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

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. Ata sete niveis de agrupamento é posible, aínda que iso pode depender da wiki ou do límite de memoria.

{{#if:string de test|retorno se string de test é non baleiro|{{#if:test string|value if test string is not empty|retorno se string de test é baleiro (ou contén soamente espazos en branco)}}}}

You can also use a parameter as the test string in your#if statement. You need to ensure you add the| (pipe symbol) after the name of the variable.(So that if the parameter does not have a value, it evaluates to an empty string instead of the string "{{{1}}}".)

{{#if:{{{1|}}}|You entered text in variable 1|There is no text in variable 1}}

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

#ifeq

Esta función de analizador compara dúas cadeas de entrada, determina se son idénticas e devolve unha das dúas cadeas en función do resultado.If more comparisons and output strings are required, consider using#switch.

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

Se ambos os dous strings son valores numéricos válidos, son 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

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

{{#ifeq: foo| bar| equal| not equal}}not equal
{{#ifeq: foo| Foo| equal| not equal}}not equal
{{#ifeq: "01"| "1"| equal| not equal}}not equal  (compare con exemplo similar arriba, sen comiñas)
{{#ifeq: 10^3| 1000| equal| not equal}}not equal  (compare cun exemplo similar anterior, con#expr que devolve primeiro un número válido)

Como exemplo práctico, considere unmodelo existenteTemplate:Timer usando o analizador para escoller entre dúas veces estándar, curta e longa.It takes the parameter as the first input to compare against the string "short" – there is no convention for the order, but it is simpler to read if the parameter goes first.The template code is defined as:

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

resulta no seguinte:

{{timer|short}}20
{{timer|20}}40
{{timer}}40
WarningWarning:Cando se usa dentro dunha función de analizador, calquera etiqueta de analizador e outras funcións de analizador deben substituírse temporalmente porun código único. Isto afecta ás comparacións:
{{#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 strings para seren comparados son dadas coma chamadas iguais ao mesmomodelo contendo tales etiquetas, entón a condición é verdadeira, pero no caso de dous modelos con contido idéntico que contén tales etiquetas é tido falso.
WarningWarning:Literal comparisons topage-name magic words may fail depending on site configuration.For example, {{FULLPAGENAME}}, depending on wiki, may capitalize the first letter, and will replace all underscores with spaces.

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

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

#iferror

Esta función toma un string de entrada e devolve un de dous resultados. A función toma comotrue se a string de entrada contén un obxecto de HTML conclass="error", a medida que é xerado por outras funcións sintácticas, coma#expr,#time e#rel2abs, erros demodelos coma bucles, recorrencias e outros erros sintácticos de "failsoft".

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

Un ou ambos os strings de retorno poden ser omitidos. Se o stringcorrecto é omitido, ostring de test é devolto se non estiver errado. Se o stringerro é tamén omitido, un string baleiro é devolto nun 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:<strongclass="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 función avalía unha expresión matemática e devolve un de dous strings, dependendo do valor binario do resultado:

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

A entrada deexpresión é avaliada exactamente como está por#expr 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 carafalse:

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

Como mencionado arriba, cero avalía carafalse e calquera valor non cero avalía caratrue, así esta función é equivalente a unha utilizando soamente#ifeq e#expr:

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

agás unha expresión de entrada baleira ou equivocada (unha mensaxe de erro é tratada coma string baleiro; non é igual a cero, así poñemosvalue if true).

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

comparando

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

Calquera ou ambos os valores de retorno poden ser omitidos; ningunha saída é dada cando o sitio apropiado é deixado baleiro:

{{#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
WarningWarning:#ifexpr non informa de comparacións numéricas equivalentes cos analizadores#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

Debido a que PHP usado en#ifeq e#switch compara dous números de tipo enteiro, devolve correctamente o resultado esperado.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.

Este comportamento en#ifexpr é causado porque MediaWiki converte os números literais en expresións en tipo float, o que, para enteiros grandes coma estes, implica redondeo.

#ifexist

SeeManual:Checking for page existence for other methods of checking if a page exists with different limitations

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.

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

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

{{#ifexist: Help:Extension:ParserFunctions/gl | exists | doesn't exist }}exists
{{#ifexist: XXHelp:Extension:ParserFunctions/glXX | exists | doesn't exist }}doesn't exist

A función trata comatrue (verdadeiro) paraHelp:System message|mensaxes de sistema que foron personalizadas, e paraHelp:Special pages|páxinas especiais que son definidas polo software.

{{#ifexist: Special:Watchlist | exists | doesn't exist }}exists
{{#ifexist: Special:CheckUser | exists | doesn't exist }}exists (porque a extensiónCheckuser está instalada nesta wiki)
{{#ifexist: MediaWiki:Copyright | exists | doesn't exist }}doesn't exist (porqueMediaWiki:Copyright non foi personalizado)

Se unha páxina comproba un destino utilizando#ifexist:, entón tal páxina aparecerá na lista Special:WhatLinksHere para a páxina de destino. Así se o código{{#ifexist:Foo}} foi incluído en tempo de execución nesta páxina (Help:Extension:ParserFunctions/gl), Special:WhatLinksHere/Foo listará Help:Extension:ParserFunctions/gl.So if the code{{#ifexist:Foo }} were included live on this page (Help:Extension:ParserFunctions/gl),Special:WhatLinksHere/Foo will list Help:Extension:ParserFunctions/gl.

En wikis que utilizan un repositorio compartido de medias,#ifexist: pode ser utilizada para comprobar se un arquivo foi cargado ó repositorio, pero non á wikide per se:

{{#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 unha páxina de descrición local foi creada para o arquivo, o resultado éexiste para tódolos ítens arriba.

#ifexist: non funciona con ligazóns de interwiki.

Limites de ifexist

#ifexist: é considerada unha "función sintáctica custosa"; soamente unha cantidade limitada dela pode ser incluída nalgunha unha páxina (incluíndo funcións dentro de modelos translucidos).Cando este límite é superado, calquera outra función#ifexist: automaticamente devolve falso, se a páxina de destino existe ou non, e a páxina é clasificada enCategory:Pages with too many expensive parser function calls.O nome datracking category pode variar dependendo da lingua do contido da wiki.

Nalgúns casos de é posíbel emular o efecto de ifexist con CSS, usando os selectoresa.new (para seleccionar as ligazóns das páxinas inexistentes) oua:not(.new) (para seleccionar as ligazóns páxinas existentes).Ademais, porque a cantidade de funcións sintácticas custosas que poden ser utilizadas nunha soa páxina é controlada por$wgExpensiveParserFunctionLimit, pódese aumentar este límite en LocalSettings.php, se for preciso.

ifexist and wanted pages

Prior to MediaWiki 1.45, a page that does not exist and is tested for using #ifexist will end up on theWanted Pages.SeeT14019 for the reason, andw:Template:Linkless exists for a workaround.

#rel2abs

Esta función converte un camiño de arquivo relativo nun absoluto.

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

Dentro da entrada depath, a sintaxe s seguir é válida:

  • .the current level
  • ..go up one level
  • /foogo down one level into the subdirectory /foo

Se non se especificabase path, utilizarase no seu lugar o nome da páxina completa:

{{#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 errónea, coma/. ou/./, é ignorada.Vez que non máis que dous puntos consecutivos son permitidos, secuencias coma estas poden ser utilizadas para separar declaracións sucesivas:

{{#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 }}Erro: Profundidade da ruta non válida: "Help:Foo/bar/baz/../../../../quok" (intentouse acceder a un nodo por riba do nodo raíz).

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

#switch

See also:w:Help:Switch parser function

Esta función proba un valor de entrada contra varios casos de test, devolvendo unha cadea asociada se unha correspondencia é atopada.

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

Estándar

Oresultado estándar é devolto se ningún string doscasos combina cóstring de comparación:

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

Nesta sintaxe, o resultado estándar debe ser o último parámetro e non debe conter un sinal de igual puro (un signo igual sen{{}}).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 estándar pode ser explicitamente declarado cun string decase para "#default".

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

Un resultado estándar declarado desta forma pode ser posto en calquera sitio dentro da función:

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

Se o parámetrodefault (estándar) é omitido e ningunha correspondencia é atopada, ningúnresult (resultado) é devolto:

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

Agrupando resultados

É posible ter valores 'malogrados', cando varias strings decase devolven a mesma cadea deresult (resultado). Isto minimiza duplicación.

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

Aquí, os casos 2, 3 e 4 todos devolvenresult234; ambos os casos 6 e 7 devolvenresult67The "#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.SeeHelp:Parser functions in templates.)

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

In the above case, if{{{1}}} equalsfoo, the function will returnFoo.If it equalsbaz, the function will returnBaz.If the parameter is empty or does not exist, the function will returnBar.

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}}} equalsfoo,zoo orroo, the function will returnFoo.If it equalsbaz, the function will returnBaz.If the parameter is empty or does not exist, the function will returnBar.

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 equalsfoo orbar, in which case it returnsFoo orBar, respectively.

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

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

If 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 comparación

Tal como con#ifeq, 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:

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

O string decase pode ser baleiro:

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

Unha vez unha correspondencia é atopada, oscases (casos) seguintes son ignorados:

{{#switch: b| f= Foo| b= Bar| b= Baz|}}Bar
WarningWarning:As comparacións numéricas con#switch e#ifeq non son equivalentes ás comparacións en expresións (véxase arriba tamén):
{{#switch: 12345678901234567| 12345678901234568= A| B}} →B
{{#ifexpr: 12345678901234567 = 12345678901234568| A| B}} →A

Sinais de igual puros

Strings de "caso" non poden conter sinais de igual puros. Para contornar isto, débese crear un modelo $tpl contendo un sinal de igual simple: $code1 ou substitúe signo igual por código html&#61;.

Exemplo:

You typeYou 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 un simple exemplo factual do uso desta función, vexa [$enwp-nba-color Template:NBA color]. Dous exemplos complexos poden ser atopados en $tpl-ext ew:Template:BOTREQ.

Substituíndo #ifeq

#switch pode ser utilizado reducirprofundidade de expansión.

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

CódigoDescriciónRetorno actual
(Limpe o cache desta páxina para actualizar)
Ano
YAno con catro díxitos2025
yAno con dous díxitos.25
L1, se é ano bisesto; 0, se non.0
o[note 1]Código ISO-8601 do ano da semana especificada.[note 2]2025[note 3]
  1. Require PHP 5.1.0 e o mais novo e arev:45208.
  2. Isto ten o mesmo valor de Y, agás que se o código ISO de semana (W) pertence ao ano anterior ou posterior, tal ano é utilizado polo outro.
  3. Sairá literalo se a nota 1 non se cumpre.
Mes
nNúmero do mes, sen cero á esquerda.7
mNúmero do mes, con cero á esquerda.07
MAbreviatura do nome do mes na lingua do sitio.xul
FNome completo do mes na lingua do sitio.xullo
xgDevolve o nome enteiro de mes na forma docaso xenitivo para linguas de sitios que distinguen entre as formas xenitiva enominativa. Esta opción é útil para moitaslinguas eslavas coma polaco, ruso, eslovaco, checo, bielorruso, esloveno, ucraíno etc.Para polaco:
{{#time:F Y|June 2010|pl}} → czerwiec 2010
(nominativo)
{{#time:d xg Y|20 June 2010|pl}} → 20 czerwca 2010
(xenitivo)
Day of the month or the year
jDía do mes, sen cero á esquerda.18
dDía do mes, con cero á esquerda.18
zDía do ano (Xaneiro 1 = 0).
Note Note: Para obter o código ISO do día do ano, sumar 1.
198
Week and day of the week
WCódigo ISO-8601 do número da semana, con cero á esquerda.29
NCódigo ISO-8601 do día da semana (luns = 1, domingo = 7)5
wNúmero do día da hebdómada (domingo = 0, sábado = 6).5
DAbreviatura do día da hebdómada. Raramente internacionalizado.ven
lNome completo do día da semana. Raramente internacionalizado.venres
Hora
a"am" durante a mañá (00:00:00 → 11:59:59), "pm" polo contrario (12:00:00 → 23:59:59).pm
AVersión en maiúsculas dea arriba.PM
gHora no formato de 12 horas, sen cero á esquerda.7
hHora no formato de 12 horas, con cero á esquerda.07
GHora no formato de 24 horas, sen cero á esquerda.19
HHora no formato de 24 horas, con cero á esquerda.19
Minutos e segundos
iMinutos pasados nunha hora, con cero á esquerda.18
sSegundos contados nun minuto, con cero á esquerda.54
UUnix time. Segundos dende 1 de xaneiro de 1970 00:00:00 GMT.1752866334
Fuso horario (des1.22wmf2)
eIdentificador de fuso horario.UTC
ISe a data é, ou non, durante o horario de verán0
ODiferenza para a hora de Greenwich (GMT)+0000
PDiferenza para a hora de Greenwich (GMT), con dous puntos+00:00
TAbreviatura do fuso horario.UTC
ZDesprazamento do fuso horario en segundos.0
Diversos
tNúmeros de días no mes actual31
cData no formato ISO-8601, equivalente aY-m-d"T"H:i:s+00:00.2025-07-18T19:18:54+00:00
rData no formatoRFC 5322, equivalente aD, j M Y H:i:s +0000, co nome do día da semana e co nome do mes non internacionalizados.Fri, 18 Jul 2025 19:18:54 +0000
Calendarios non gregorianos
Islámico
xmjDía do mes22
xmFNome completo do mesMuharram
xmnNúmero do mes.1
xmYAno completo.1447
Iraniano (Jalaly)
xitNumber of days in the month.31
xizDay of the year.119
xijDía do mes27
xiFNome completo do mesTir
xinNúmero do mes.4
xiYAno completo1404
xiyAno con dous díxitos.04
Hebreo
xjjDía do mes22
xjFNome completo do mes.Tamuz
xjtNúmero de días no mes.29
xjxForma xenitiva do nome de mes.Tamuz
xjnNúmero do mes10
xjYAno completo5785
Calendario solar tailandés
xkYAno completo nocalendario solar tailandés.
Note Note: Para os anos antes de 1941 as datas na escala Jan-Mar non son bencalculadas.
2568
Ano Minguo/Juche
xoYAno completo.114
Calendario xaponés (nengo)
xtYAno completo.令和7
Flags
xnFormata o seguinte código numérico coma número de ASCII puro.Na lingua hindú,{{#time:H, xnH}} fai ०६, 06.
xNComaxn, pero como unha flag alternada, que dura ata o fin do string ou ata a seguinte aparición dexN no string.
xrFormata o número seguinte coma número romano. Soamente funciona para números ata 10.000
(ata 3.000 antes de MediaWiki 1.20).
{{#time:xrY}} → MMXXV
xhFormata o número seguinte en números hebreos.{{#time:xhY}} → ב'כ"ה

Esta función sintáctica toma unha data e/ou hora (no calendario gregoriano) e formata conforme a sintaxe dada. Un obxecto de data/hora pode ser especificado; o estándar é o valor dapalabra máxica{{CURRENTTIMESTAMP}} – é dicir, a hora na que a páxina foi por último traducída en 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 formato aceptados é dada na táboa á dereita.Calquera carácter na texto so formato que non é recoñecida é pasado completamente inalterado; isto aplícase para tamén borrar espazos (o sistema non os necesita para interpretar os códigos).If no character is recognized in the formatting string, and the date/time object is without error, then the formatting string is returned as output.Hai tamén dúas formas de escaparse de carácteres dentro do texto formato:

  1. Unha barra invertida seguido por un carácter é interpretado exactamente coma un único carácter
  2. Caracteres entre comiñas son considerados caracteres literais, e as comiñas son sacadas.

Ademais, o dígrafoxx é interpretado como un só carácter "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}}2025-07-18
{{#time:[[Y]] m d}}2025 07 18
{{#time:[[Y (year)]]}}2025 (25UTCpmFri, 18 Jul 2025 19:18:54 +0000)
{{#time:[[Y "(year)"]]}}2025 (year)
{{#time: i's"}}18'54"

Thedate/time object can be in any format accepted by PHP'sstrtotime() function.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, 18 Jul 2025 19:18:55 +0000
{{#time: r|+2 hours}}Fri, 18 Jul 2025 21:18:55 +0000
{{#time: r|now + 2 hours}}Fri, 18 Jul 2025 21:18:55 +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}}Erro: Hora non válida.
{{#time: r|last tuesday}}Tue, 15 Jul 2025 00:00:00 +0000

Ocódigo da lingua enISO 639-3 (?) permite mostrar o texto na lingua escollida

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

Thelocal parameter specifies if thedate/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 theofficial PHP documentation for details on how string are cast to boolean values).

Please note that, if the variable$wgLocaltimezone is set toUTC, there is no difference in the output whenlocal is set totrue orfalse.

See the following examples for details:

{{#time: Y F d H:i:s|now|it|0}}2025 luglio 18 19:18:55
{{#time: Y F d H:i:s|now|it|1}}2025 luglio 18 19:18:55
{{#time: Y F d H:i:s|+2 hours||0}}2025 xullo 18 21:18:55
{{#time: Y F d H:i:s|+2 hours||1}}2025 xullo 18 21:18:55
{{#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 xa se calculou un data e hora en Unix, pódese utilizar esta forma de cálculo en operacións con data preto coa anteposición do símbolo@.

{{#time: U| now}}1752866335
{{#time: r | @1752866334 }}Fri, 18 Jul 2025 19:18:54 +0000
WarningWarning:

Without the@ prefix before numeric timestamp values, the result is an error most of the time, or is an unexpected value:

{{#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(correct)
{{#time: r | 999 }}Erro: Hora non válida.(unsupported year format)
{{#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(correct)
{{#time: r | 1000 }}Fri, 18 Jul 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(correct)
{{#time: r | 9999 }}Sun, 18 Jul 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(correct)
{{#time: r | 10000 }}Erro: Hora non válida.(unsupported year format)
WarningWarning:O intervalo de entrada aceptable é 1 de xaneiro de 0111 ata 31 de decembro de 9999. Para os anos de 100 a 110 a saída é incoherente, Y e anos bisestos son coma os anos 100-110, r, D, l e U son coma interpretar estes anos coma 2000-2010.
{{#time: d F Y| 29 Feb 0100}}01 marzo 0100
(correcto, ano común), pero
{{#time: r| 29 Feb 0100}}Mon, 01 Mar 0100 00:00:00 +0000 (erróneo, aínda que o ano 100 sexa interpretado coma 2000, pois é un ano bisesto)
{{#time: d F Y| 15 April 10000}}Erro: Hora non válida.
{{#time: r| 10000-4-15}}Sat, 15 Apr 2000 10:00:00 +0000

Os números do ano 0-99 interprétanse como 2000-2069 e 1970-1999, excepto cando se escriben en formato de 4 díxitos con ceros ao principio:

{{#time: d F Y| 1 Jan 6}}01 xaneiro 2006
{{#time: d F Y| 1 Jan 06}}01 xaneiro 2006
{{#time: d F Y| 1 Jan 006}}01 xaneiro 2006
{{#time: d F Y| 1 Jan 0006}}01 xaneiro 0006 (4-digit format)
O día da hebdómada é soportado para os anos entre 100 e 110 e des 1753. Para os anos entre 111 e 1752 o retorno á dereita mostra "Unknown" e o da esquerda, "<>". Como consecuencia, o retorno á dereita non é aceptado para entrada destes anos.

Datas absolutas completas ou non poden ser especificadas; a función "completará" as partes da data que non son dadas, utilizándose dos valoresactuais:

{{#time: Y| January 1}}2025
WarningWarning:O recurso de complemento non é consistente. Algunhas partes son cubertas cos valores actuais; outras, non:
{{#time: Y m d H:i:s| June}}2025 06 18 00:00:00 Devolve o comezo do día, pero para o día presente do mes e do ano actuais.
{{#time: Y m d H:i:s| 2003}}2003 07 18 00:00:00 Devolve o comezo do día, pero para o presente día do ano actual.

There's exception case of the filled day:

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

Un número de catro díxitos será interpretado coma un ano, endexamais coma hora e minutos:[1]

{{#time: Y m d H:i:s| 1959}}1959 07 18 00:00:00

Un número de seis díxitos é interpretado coma horas, minutos e segundos, se posíbel, pero, por outra banda, coma un erro (non, por exemplo, un ano e un mes):

{{#time: Y m d H:i:s| 195909}}2025 07 18 19:59:09 A entrada é tida coma unha hora máis do que un código de ano+mes.
{{#time: Y m d H:i:s| 196009}}Erro: Hora non válida. Aínda que 19:60:09 non sexa unha hora válida, 196009 non é interpretado coma setembro de 1960.

A función realiza un certo número de operacións con data:

{{#time: d F Y| January 0 2008}}31 decembro 2007
{{#time: d F| January 32}}Erro: Hora non válida.
{{#time: d F| February 29 2008}}29 febreiro
{{#time: d F| February 29 2007}}01 marzo
{{#time:Y-F|now -1 months}}2025-xuño

A achura total do textos de formato das chamadas de#time é limitada a 6000 caracteres[1].

Choiando con fusos horarios

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

  • {{#time:g:i A| -4 hours}} → 3:18 PM

However, India is on a +5.5 hours time offset from UTC, and thus using its time zone will not normally allow the correct calculation of a relative time zone offset. Here's what happens:

  • {{#time:g:i A| +5.5 hours}} → 7:18 PM

Para contornar esta situación, pódese converter o tempo en minutos ou segundos, así:

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

(Tim Starling, o desenvolvedor desta función, forneceu a sintaxe exacta para esta solución.)

#time format like in signatures

Sometimes it is useful to construct a timestamp, which looks like the automatic timestamp generated bysignatures in discussions on talk pages.On an English-language wiki, it can be created with:

  • {{#timel:H:i, j xg Y (e)|+330 minutes}} → 00:48, 19 xullo 2025 (UTC)

#timel

This function is identical to{{#time: ... }} with thelocal parameter set totrue, so it always uses the local time of the wiki (as set in$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 toUTC, there is no difference in the output whenlocal is set totrue orfalse
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}}2025-07-18T19:18:55+00:00
{{#time:c|now|it|0}}2025-07-18T19:18:55+00:00
{{#time:c|now|it|1}}2025-07-18T19:18:55+00:00
{{#timel:c|now|it}}2025-07-18T19:18:55+00:00
Warning Example fromhttps://no.wikipedia.org/wiki/Maldiskusjon:Sommertid
WarningWarning:

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)

UUnix time. Seconds since January 1 1970 00:00:00 GMT.
ZTimezone offset in seconds.
{{#time: U}}1752866334
{{#timel: U}}1752866334
{{#time: Z}}0
{{#timel: Z}}0

#timef

This function formats a date using a standard format for the selected language, as defined in$dateFormats (seeT223772).

{{#timef:date/time object }}
{{#timef:date/time object |format type }}
{{#timef:date/time object |format type |language code }}

The format of thedate/time object is the same as for#time. If it is empty, the time when the page was rendered is used.

Theformat type may be one of:

time
Only the time is shown.
date
Only the date is shown.
both
Both the time and date are shown.
pretty
Only the date is shown, using an abbreviated format which does not include the year.Not all languages support this; if it is not supported, the "date" format is used.

If theformat type is not specified, both the time and date will be show, as ifboth were specified.

If thelanguage code is not specified, the page's content language is used.

Using#timef instead of#time allows templates to more easily support multiple languages, since different languages have different ways to format dates.

In English, the order of the day and month is controlled by$wgAmericanDates.

Examples:

{{#timef:now|both|en}} 19:18, 18 July 2025
{{#timef:now|both|ja}} 2025年7月18日 (金) 19:18
{{#timef:now|pretty|en}} 18 July
{{#timef:now|pretty|pl}} 18 lipca
{{#timef:|time}} 19:18

#timefl

This function is the same as#timef except that it uses the local timezone of the wiki as configured in$wgLocaltimezone.

{{#timefl:date/time object }}
{{#timefl:date/time object |format type }}
{{#timefl:date/time object |format type |language code }}

#titleparts

Esta función divide o título da páxina en segmentos baseados no carácter de barra, entón devolve algúns deses segmentos.

{{#titleparts:pagename |number of segments to return |segment to start at }}

If thenumber of segments to return parameter is not specified, it defaults to "0", which returns all the segments from thesegment to start at to the end (included). If thesegment to start at parameter is not specified or is "0", it defaults to "1":

{{#titleparts:Talk:Foo/bar/baz/quok }}Talk:Foo/bar/baz/quok
{{#titleparts:Talk:Foo/bar/baz/quok | 1 }}Talk:FooSee 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 | 3 }}baz/quok
{{#titleparts: Talk:Foo/bar/baz/quok | 3 | 2 }}bar/baz/quok
{{#titleparts: Talk:Foo/bar/baz/quok | | 2 }}bar/baz/quok
{{#titleparts: Talk:Foo/bar/baz/quok | | 5 }}

Valores negativos son aceptados para ambos os valores. Valores negativos paranumber of segments decotan efectivamente segmentos do fin do texto. Valores negativos parafirst segment traduce para "empezar con este segmento contando da dereita":

{{#titleparts:Talk:Foo/bar/baz/quok | -1 }}Talk:Foo/bar/baz Elimina un segmento do fin do string. Véxase tamén {{BASEPAGENAME}}.
{{#titleparts: Talk:Foo/bar/baz/quok | -4 }} Elimina os 4 segmentos do fin do string
{{#titleparts: Talk:Foo/bar/baz/quok | -5 }} Elimina 5 segmentos do fin do string (máis do que existen)
{{#titleparts: Talk:Foo/bar/baz/quok | | -1 }} quok Devolve o último segmento. Véxase tamén {{SUBPAGENAME}}.
{{#titleparts: Talk:Foo/bar/baz/quok | -1 | 2 }} bar/baz Elimina un segmento do fin do string, entón devolve do segundo segmento en diante
{{#titleparts: Talk:Foo/bar/baz/quok | -1 | -2 }} baz Empeza a copiar no segundo último elemento; extrae un segmento do fin do string

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

For example, any occurrence of&quot;,&#34;, or&#x22; inpagename 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.

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 isCategory: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 returning1; (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 returning1; (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 return1 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 stillunconditionally 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 stringCategory:Côte-d&apos;Or and not the expectedCategory: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 decodedpagename 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 booNot bah_boo, despite the underscore in the original.
  2. O texto de entrata posúe o límite de 25 cortes; as barras a máis son ignoradas e o 25º elemento conterá o resto do texto. O texto é tamén limitado a 255 caracteres, e é tratado como untítulo de páxina:
    {{#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 calquera razón necesítase forzar esta función ó seu límite, aínda que moi improbable, é posible contornar o límite de 25 cortes agrupándose unha función dentro doutra:
    {{#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
Pódese utilizar #titleparts como un pequeno "texto analítico e conversor", mais débese considerar que devolve a primeira parte capitalizada.
{{#titleparts:one/two/three/four|1|1 }}One
{{#titleparts: one/two/three/four|1|2 }}two

Se letras minúsculas son imprescindíbeis, débese usar a función lc: para axustar o retorno.

{{lc: {{#titleparts:one/two/three/four|1|1 }} }}one

You can prepend a 'dummy' slash at the beginning of the string to get the correct first substring capitalization (uppercase or lowercase). Use2 instead of1 forfirst segment to return:

{{#titleparts:/one/two/three/four|1|2 }}one
{{#titleparts:/One/two/three/four|1|2 }}One
WarningWarning:Certos caracteres que son ilegais nun título de páxina farán con que #titleparts non analice o string:
{{#titleparts: {one/two} | 1 | 1 }}{one/two}. Non retorna o resultado 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 inputpagename 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.
WarningWarning:

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
WarningWarning:Esta función non se degrada ordinariamente se a súa entrada supera 255 carácteres. Se o texto for maior que 256 caracteres, esta función sinxelamente retornará o mesmo texto.


String functions

Main page:Extension:ParserFunctions/String functions

The ParserFunctions extension optionally defines various string functions if$wgPFEnableStringFunctions is set totrue:

  • #len
  • #pos
  • #rpos
  • #sub
  • #count
  • #replace
  • #explode
  • #urldecode

See the dedicated subpage for documentation, andManual:Performing string operations with parser functions for examples.

WarningWarning:In 2013, it was decided thatthese functions willnever be enabled on any Wikimedia wiki, because they are inefficient when used on a large scale (seephab:T8455 for some history).These functions do NOT work on Wikimedia wikis!

If you are here to write something on a Wikimedia project, you are looking for something else: if your home wiki has string functions, it probably usesLua.For example, the English Wikipedia usesModule:String, which does some of the same things with wildly different syntax.There are also individualString-handling templates.

Here is a short overview ofModule:String functions:

  • #len(length of string):{{#invoke:String|len|target_string}}
  • #sub(substring):{{#invoke:String|sub|target_string|start_index|end_index}}
  • #match:{{#invoke:String|match|source_string|pattern_string|start_index|match_number|plain_flag|nomatch_output}}
  • #pos(position of target):{{#invoke:String|pos|target_string|index_value}}
  • #find:{{#invoke:String|find|source_string|target_string|start_index|plain_flag}}
  • #replace:{{#invoke:String|replace|source_str|pattern_string|replace_string|replacement_count|plain_flag}}
  • #rep(repeat):{{#invoke:String|rep|source|count}}
  • #escapePattern:{{#invoke:String|escapePattern|pattern_string}}
  • #count:{{#invoke:String|count|source_str|pattern_string|plain_flag}}
  • #join:{{#invoke:String|join|separator|string1|string2|...}}

Aspectos xerais

Substitución

As funcións sintácticas poden sersubstituídas engadindose o termosubst: antes do carácter #;

{{subst:#ifexist: Help:Extension:ParserFunctions/gl | [[Help:Extension:ParserFunctions/gl]] | Help:Extension:ParserFunctions/gl }} → o código[[Help:Extension:ParserFunctions/gl]] será engadido no texto wiki se a páxina Help:Extension:ParserFunctions/gl existir.
WarningWarning:Os resultados das funcións sintácticas substituídas son indefinidos se as expresións conteñen código volátilnon substituído, comavariables ou outra función. Para resultados coherentes, débese substituír todolo código volátil na expresión so avaliación. VéxaseAxuda:Substitución.

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

Redireccións

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

Elidindo o carácter de barra vertical en táboas

In tables

As funcións sintácticas estragarán as sintaxe detáboas wiki e caracteres de barra vertical (|), tratando tódolas barras verticais coma divisores de parámetros.To avoid this, most wikis used a templateTemplate:! with its contents only a raw pipe character (|), since MW 1.24 a{{!}} magic word replaced this kludge.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:&#124;.

DescriciónEscribíndoseObtense
Elidindo o carácter de barra vertical coma divisor de liña/columna
{{!}}
|
Elidindo o carácter de barra vertical coma un carácter simple
&#124;
|

In template calls

The same pipe protection applies as for the following example:

{{Documentation|content=... text before ...<code>subpage-name=sandbox3</code> is equivalent to <code>sandbox link=../sandbox3 | sandbox name=sandbox3</code>.... text after ...}}

We observe thattext after is not displayed when the pipe | just beforesandbox name= is present since|sandbox name= is considered erroneously to be a parameter of templateDocumentation at the same level as|content= is.

Eliminación de espazos en branco

Espazos en branco, incluíndose os caracteres de liña nova, tabuladores e espazo, son elididos antes e despois de cada un dos parámetros das funcións sintácticas. Para impedir que tal suceda, as comparacións de texto poden ser feitas engadindo comiñas.

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

To prevent the trimming of then and else parts, seem: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

Pero este método soamente permite a interpretación deun espazo en branco, pois a función sintáctica reduce espazos múltiples a un só.

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

Neste exemplo, o estilowhite-space: pre é utilizado para formar con que os espazos en branco sexan preservados polo navegador, aínda así os espazos non son mostrados. Isto sucede porque os espazos son eliminados polo software, antes de envialos ó explorador.

É posíbel contornar este comportamento cambiando espazos en branco por&#32; (carácter de espazo, ouespazo crebadizo) ou&nbsp; (espazo sen quebra, ouespazo ríxido), pois non son modificados polo software:

<spanstyle="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.Intemplates, whitespace at the beginning and end is stripped for named parameters and named unnamed parameters butnot from unnamed parameters:

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

Other parser functions

Case conversion functions

  • Lowercase:"{{lc: AbC}}" → "abc"[2]
  • Uppercase:"{{uc: AbC}}" → "ABC"[3]
  • Lowercase first character:"{{lcfirst: AbC}}" → "abC"[4]
  • Uppercase first character:"{{ucfirst: abc}}" → "Abc"[5]

Encoding functions

  • URL encoding:
"{{urlencode: AbCdEf ghi}}"

renders as


"AbC%0AdEf+ghi"


So inner new lines convert into %0A, and inner spaces convert into +.

Anchor encoding

{{anchorencode: AbC dEf ghi}}

renders as


AbC_dEf_ghi


Véxase tamén

References

  1. Antes der86805 en 2011 este non era o caso.
All
See also
Retrieved from "https://www.mediawiki.org/w/index.php?title=Help:Extension:ParserFunctions/gl&oldid=7751115"
Categories:

[8]ページ先頭

©2009-2025 Movatter.jp