Help:Advanced templates/pt-br

Manual do MediaWiki: Conteúdo, Leitores, Editores, Moderadores, Administradores, Pesquisadores +/-

Esta página cobre técnicas avançadas para predefinições, em particular o uso de nomes de variáveis e os nomes de parâmetros nas predefinições. Os leitores devem estar familiarizados com as técnicas padrão de predefinições encontrado em Help:Template. Algumas técnicas descritas abaixo podem estar desatualizadas ou de uso limitado, por exemplo, ParserFunctions pode ser mais conveniente do que algumas das técnicas de ramificação discutidas.

Em geral, estas técnicas dependem do processamento recursivo (de dentro para fora) de predefinições. Quando uma predefinição é expandida (processada), ela traduz o código em valores de string. Estes são frequentemente enviados diretamente para o navegador web para exibição, mas podem ser tratados como código propriamente dito. Colocando as cadeias de texto entre chaves duplas ({{}}), por exemplo, podem ser reprocessados como nomes de predefinições ou nomes de variáveis, produzindo resultados diferentes, sempre que os valores da seqüência são alterados.

Nota:

  • Este documento refere-se as características atualmente somente disponíveis no software Mediawiki a partir da versão 1.6 e posteriores.
  • O termo "variável" tem dois usos neste documento:
    • Como substantivo que significa um tipo de palavra mágica, que é uma variável de sistema que podem ser acessada da mesma maneira como modelos (assim {{NAMESPACE}} irá retornar o nome do namespace atual, dependendo da página).
    • Como adjetivo ou advérbio, ela é usada no sentido geral, para indicar que algo pode variar com o contexto (portanto, um "nome de variável" significa que o nome da predefinição que está sendo chamada pode mudar de acordo com parâmetros ou variáveis).
  • A utilização de "subst": com recursividade manual realiza uma substituição gradual, útil para analisar e explicar o funcionamento das predefinições chamando outras predefinições. Por exemplo, compare {{{{TCTC}}}} (discutido abaixo) com {{{{subst:TCTC}}}} em uma página Sandbox. Embora ambos produzam o mesmo resultado, o primeiro permanecerá como o código completo {{{{TCTC}}}}, enquanto o segundo irá substituir a predefinição interna {{TCTC}} com o seu valor, deixando o código {{tc}}. Veja, por exemplo, Template talk:Lop.

Predefinições variáveis edit

Em alguns casos, pode ser útil para uma predefinição chamar diferentes predefinições dependendo de uma variável ou parâmetro fornecido. This allows a type of branching that can be simpler than with ParserFunctions, though they are generally less versatile.

Examples:

Using a variable to choose a template - {{ {{NAMESPACE}} }}
The magic word {{NAMESPACE}} returns the current namespace, like so: {{NAMESPACE}} = Help. The outer brackets then process this result as a template in its own right - in this case Template:Help - which produces This phrase is the contents of Template:Help.
Using a template to choose a template - {{{{tctc}} }}
the template {{Tctc}} contains the text "tc". This text is processed by the outer brackets as Template:tc which contains the word "in".

The extra spaces in the above examples are needed: without them, the pair of inner three braces is taken as those for a parameter. On the page itself it just shows as plain text: {{{{NAMESPACE}}}}.

Using a parameter to choose a template - {{{{{2}}}x|{{{1}}}}}
The second parameter passed becomes part of the template name to which the first parameter is passed. In this case {{2x|{{{1}}}}} would produce {{{1}}}{{{1}}}, {{3x|{{{1}}}}} would produce {{{1}}}{{{1}}}{{{1}}}, and etc. Template:Histogram uses this technique repeatedly in {{histogram|X|4|7|3|2|9}} to produce the following 5 line histogram:

XXXX

XXXXXXX
XXX
XX

XXXXXXXXX

Using parser functions and templates, including those which process strings (see Help:String functions and Category:String manipulation templates), a template name can also depend in a more complicated way on parameters and/or variables.

Templates passed as parameters edit

Templates can be passed as parameters to other templates. This can mean either that the template is evaluated and the result is passed as a parameter or that the template name is passed and evaluated as part of the other template.

Passing a template result - {{3x|{{tc}}}}
Template:3x contains {{{1}}}{{{1}}}{{{1}}}. {{3x|{{tc}}}} first evaluates {{tc}} (which yields the word in), and passes that to template {{3x}}, to give ininin
Passing a template result recursively - {{3x|{{5x|{{tc}}}}}}
Just as above except {{tc}} (in) is first passed to {{5x}} and the result of that is passed to {{3x}}, to give ininininininininininininininin.
Passing a template name - {{tto|t|V}}
Template:tto - {{{{{1}}}|a{{{2}}}b{{{2}}}c{{{2}}}d}} - takes the value V (passed as the second parameter) and produces aVbVcVd. This value is then passed to template:t (which was passed by name as the first parameter), producing "start-aVbVcVd-end"

Variable parameter name edit

A parameter name in a template can be the value of another parameter. This is useful if you want the behavior of a template to change based on the information that is provided to it.

Choosing parameters contextually - {{t pnd|parameter name}}

Template:t p contains {{{capital}}} is the capital of {{{country}}}, with two parameters - "capital" and "country". Template:t pnd containing "{{t p|{{{1}}}=abc}}" can be used to select which parameter is used in a particular case. Thus:

This... Produces this
{{t pnd|capital}} abc is the capital of {{{country}}}.
{{t pnd|country}} {{{capital}}} is the capital of abc.
{{t pnd|something else}} {{{capital}}} is the capital of {{{country}}}.

This applies to integer parameters as well, since integer parameters can be specified using the "#=" notation. Passing the integer value N to {{t pnd}} as its parameter will make it look for the Nth unnamed parameter.

Parameter name from another parameter in the same template - {{ppp|p=foo|foo=bar}}
using Template:ppp, which contains {{{{{{p}}}}}}, the code bar will first set the parameter named "foo" to the value "bar", and then set the parameter named "p" to the value of foo, yielding bar. The order in which the parameters appear in the code does not matter, but the technique cannot be applied multiple times—e.g., using Template:tvvv, which contains {{{{{{{{{p}}}}}}}}}, {{tvvv|p=foo|foo=bar|bar=biz}} gives biz.

This is e.g. applied in w:Template:Reg polyhedra db, which contains a 2D array in the form {{{{{1}}}|{{{2}}}|1-1=a11|..|m-n=amn}}. The first parameter is the name of a template that provides a particular selection and presentation of a selected row of the array, e.g. w:Template:Reg polyhedron stat table, the second parameter (which is the first parameter of the latter template) specifies the row. The latter templates references element j of the row concerned by a tag of the form {{{{{{1}}}-j}}}

Whilst the same output could also be produced using {#switch:}, this method is less intensive on the server and may help to stay under page limits; see Help:Array.

Branching techniques without ParserFunctions edit

The parameter default feature was introduced before Extension:ParserFunctions. This led to the development of branching methods through the parameter default mechanism.

If-defined branches - {{{test{{{test|}}}|{{{then}}}}}}
If no value is passed for the parameter test, then {{{test{{{test|}}}|{{{then}}}}}} resolves to {{{test|{{{then}}}}}} and returns a blank entry (since test is defined as blank). If the parameter "test" is assigned the value "boo", however, {{{test{{{test|}}}|{{{then}}}}}} resolves to {{{testboo|{{{then}}}}}}, and so long as no parameter "testboo" exists, then this will return the value of the parameter "then".

See Template:Ifwpc for comparisons.

There was also an array technique using parameter defaults, with the disadvantage that a template using this technique had to be called with, in addition to the normal parameters, a standard parameter definition not reflecting a choice, but necessary to make the template work.

An even older branching technique dates from before the introduction of the parameter default mechanism. It is based on the fact that if in a template call a parameter is assigned a value more than once, the last one counts. This is used in combination with specifying the value of a parameter in a template call, where the name of that parameter depends on a parameter of an outer template. In a call {{a|b=c|{{{d}}}=e}}, template:a uses b=c if b?{{{d}}} and b=e if b={{{d}}}. See Template:T pdc.

Another old "branching technique" is using a template name depending on the value of a parameter (see above).

Variable variable names edit

Magic word depending on a template - {{t curr}}
Template:t curr containing "{{CURRENT{{{1|DAY}}} }}<noinclude>[[Category:Test pages]]</noinclude>" gives the text 29 without parameters, since it defaults to {{CURRENTDAY}}, but {{t curr|DAYNAME}} gives Friday while {{t curr|MONTHNAME}} gives March. Any magic word that begins with "CURRENT" can be accessed this way.
Parser function parameter depending on a template parameter - {{ns:{{{1}}}}}
In Template:Namespace, which contains "namespace number:{{{1}}} - name: {{ns:{{{1}}}}}", {{namespace|4}} gives "namespace number:4 - name: Meta", because Meta is the name of namespace 4.

External examples edit


See also edit


Links para outras páginas de ajuda edit

Conteúdos da Ajuda
Meta · Wikinotícias · Wikipédia · Wikiqcitações · Wikcionário · Commons: · Wikidados · MediaWiki · Wikilivros · Wikisource · MediaWiki: Manual · Google
Versões desta página de ajuda (para outros idiomas, veja mais)
Lisks no Meta ou de Meta · Wikipédia · MediaWiki
Leitura
Ir · Pesquisar · Espaço Nominal · Nome da Página · Secção · Backlinks · Redirecionamentos · Categoria · Página da Imagem · Páginas especiais · Versão Imprimível
Monitorizar alterações
Alterações recentes (otimizadas) | Mudanças relacionadas · Páginas de vigia · Diferenças · Histórico da página · Resumo da edição · Contribuições do utilizador · Edição menor · Edição patrulhada
Cadastrar e preferências
Entrar · Preferências · Estilo do usuário
Edição
Começar uma nova página · Edição avançada · Editar as «Perguntas Mais Frequentes» · Exportar · Importar · Atalhos · Conflito de Edição · Tamanho da página
Referenciar
Link · URL · Link associados · Adicionar Interwiki · Notas de Rodapé
Estilo e formatação
Exemplos de Texto da Wiki · CSS · Cartão de referência · HTML no Texto da Wiki · Fórmula · Lista · Tabela · Ordenação · Cores · Envios de Arquivos e imagens
Corrigir erros
Mostra Pré-visualização · Testes · Reverter edições
Funionamento avançado
Expansão · Modelo · Predefinições avançadas · Função do analisador · Parâmetro Predefinido · Variável · Mensagem do sistema · Substituição · Array · Calculo · Integrar página
Outros
Carateres Especiais · Renomear (mover) uma página · Preparar uma página para tradução · Página de Discussão · Assinaturas · Página de Testes (Sandbox) · Problemas legais para os editores
Other languages: