Extensão:Variables

From mediawiki.org
This page is a translated version of the page Extension:Variables and the translation is 59% complete.
Outdated translations are marked like this.
Manual de extensões do MediaWiki
Variables
Estado da versão: estável
Implementação Função de análise sintática
Descrição Apresenta funções de analisador para lidar com variáveis de escopo de página.
Autor(es)
Mantenedor(es) MGChecker
Última versão 2.5.1 (2019-07-11)
MediaWiki 1.29+
PHP 5.5+
Modifica o banco
de dados
Não
Composer mediawiki/variables
Licença Licença ISC
Download
README
RELEASE-NOTES
  • $wgVariablesAreVolatile
  • $wgVariablesDisabledFunctions
Quarterly downloads 134 (Ranked 53rd)
Public wikis using 1,808 (Ranked 201st)
Para traduzir a extensão Variables, verifique sua disponibilidade no translatewiki.net
Função no Vagrant variables
Problemas Tarefas em aberto · Relatar um bug
Atenção Atenção: This extension is incompatible with plans to parallelize parsing, as is intended by the use of Parsoid . Therefore, the future of this extension is uncertain, and it is expected to become incompatible with the standard MediaWiki parser within a few years. For further information, see tarefa T250963 and Parsoid/Extension API § No support for sequential, in-order processing of extension tags .
To avoid deprecation warning about the InternalParseBeforeSanitize hook for MediaWiki 1.35 - MediaWiki 1.38 , or missing the #var_final parser function in MediaWiki 1.39 +, please update to the latest version (master branch for now). See tarefa T276627 and tarefa T250963 for further information.

A extensão Variables ​​permite definir uma variável em uma página, usá-la mais tarde na mesma página ou predefinições incluídas, alterar o seu valor, possivelmente para um valor determinado por uma expressão em termos do valor antigo, etc

É muito parecido com uma predefinição, apenas é muito leve e com escopo para apenas uma única página, assim você pode usar muitas variáveis ​​em uma página, sem abrandar o wiki com um grande número de predefinições. Combine esta extensão com a extensão Extensão:ParserFunctions para melhores resultados.

This extension will not be enabled for wikis run by the Wikimedia Foundation (WMF).[1][2][3][4] See alternatives.

Atribuindo um valor a uma variável

#vardefine

  • {{#vardefine:nomedavariável | valorespecificado }}

Atribui o valor valorespecificado para a (já existente ou apresentada) variável nomedavariável.

  • Exemplo: {{#vardefine:iconwidth|25}} making iconwidth = 25

#vardefineecho

  • {{#vardefineecho:nomedavariável | valorespecificado }}

Funciona exatamente como #vardefine, mas o valor afetado é impresso.

  • Exemplo: making iconwidth = {{#vardefineecho:iconwidth|25}}

Recuperando o valor de uma variável

#var

O valor da variável nomedavariável é produzido por

  • {{#var:nomedavariável}}

Se indefinida, produz uma string vazia; ela não retorna uma mensagem de erro.

É possível definir um valor para o caso em que a variável não está definida ou está vazia:

  • {{#var:nomedavariável | valorpadrão }}

Isto é equivalente a

  • {{#if: {{#var:nomedavariável }} | {{#var:nomedavariável }} | valorpadrão }}

mas é muito mais curto e melhor organizado. Antes da versão 2.0, no entanto, o valor padrão sempre foi expandido. A partir da versão 2.0, o padrão só se expande no caso de ser realmente utilizado.

O valor pode ser usado em funções do analisador, etc

#varexists

  • {{#varexists:nomedavariável }} retorna 1 se a variável já estiver definida. Se a variável não for definida, o valor de retorno é nulo.

It supports a second and a third parameter to replace these values.

  • {{#varexists:variablename | if-value | else-value }}

This is equivalent to:

  • {{#if: {{#varexists: variablename }} | if-value | else-value }}

but it is much shorter and better arranged. Before version 2.5 though, both were always expanded. From version 2.5 on the if and else values only get expanded when their cases are actually entered.

#var_final

Nova função experimental introduzida em Variables 2.0. Esta função retornará o último valor que uma variável tem no final da renderização da página. Naturalmente, o valor será inserido após o analisador passar por toda a marcação wiki, por isso, esta função não pode ser usada em outras funções, esperando que o valor correto esteja sendo usado. Exemplo:

  • {{#var_final:nomedavariável | defaultvalue }}

O valor padrão será utilizado se a variável não existir na fase de renderização da página final ou se o valor for uma string vazia. O padrão será expandido exatamente onde a função é usada, de modo que o parâmetro será ampliado, mesmo que isso não for necessário.

Exemplos

A extensão Extensão:ParserFunctions também deve estar instalada para utilizar #expr.

Computar x = 2*a + b:

  • {{#vardefine:x|{{#expr:2*{{#var:a}}+{{#var:b}}}}}}

Adicionar um a n:

  • {{#vardefine:n|{{#expr:{{#var:n}}+1}}}}

Instalação

  • Baixe e coloque o(s) arquivo(s) num diretório chamado Variables na sua pasta extensions/.
    Developers and code contributors should install the extension from Git instead, using:cd extensions/
    git clone https://gerrit.wikimedia.org/r/mediawiki/extensions/Variables
  • Adicione o seguinte código ao final do seu arquivo LocalSettings.php :
    wfLoadExtension( 'Variables' );
    
  • Configure as required
  • Yes Concluído – Navegue à página Special:Version em sua wiki para verificar se a instalação da extensão foi bem sucedida.

Configuration

This extension provides two configuration parameters:

$egVariablesAreVolatile
Allows to disable the parser frame being marked as volatile by the extension, i.e. disable template caching.
Default: true;
$egVariablesDisabledFunctions
Permite desativar as funções especificadas do analisador fornecidas por esta extensão.
Default: [];
Example: [ 'var_final', 'vardefineecho' ];

Compatibility

The recommended version of the Variables extension for recent MediaWiki releases is listed below. Older versions of the extensions might work as well, but aren't tested for new MediaWiki releases.

Alternatives

As this extension will not be enabled for wikis run by the Wikimedia Foundation (WMF), here are some alternatives:[1][2][3][4]

  • If you use Variables as cache for expensive operations, you can transform the section where you need them into a template and pass the required information as template parameters instead. This will work until you reach the expansion depth limit, which can be increased if necessary.
  • If you use Variables to do more complex template operations than possible with simple Extensão:ParserFunctions , and if you have sufficient permissions on the server, you can use Scribunto's Lua functionality instead. You may not be able to install Scribunto on shared hosting. Note that this does not add support for global Variables. However, Extension:VariablesLua adds a Scribunto interface for the Variables store.
  • Não use variáveis, em vez disso, duplique as informações necessárias como uma variável. Se essas informações forem adquiridas por uma chamada de modelo cara, o desempenho poderá sofrer. Isso funcionará até você atingir o limite de contagem de nós.
  • If you require variables just for autonumbering, you could look into Extension:NumerAlpha .

Ver também

Referências