Manuale:Parole magiche

From mediawiki.org
This page is a translated version of the page Manual:Magic words and the translation is 44% complete.
Outdated translations are marked like this.
Estensioni di MediaWiki

Le parole magiche sono una tecnica per mappare una varietà di stringhe di testo wiki in un singolo ID associato a una funzione. Le variabili e funzioni parser utilizzano questa tecnica. Tutto il testo mappato a quell'ID verrà sostituito con il valore restituito dalla funzione. The mapping between the text strings and the ID is stored in the variable $magicWords in a file that can be loaded using $wgExtensionMessagesFiles[] .

Le parole magiche predefinite sono implementate in CoreParserFunctions.php .

Come funzionano le parole magiche

Ogni volta che MediaWiki trova il testo tra doppie parentesi ({{XXX ...}}) deve decidere se XXX è una variabile, funzione parser o template. Per fare ciò, pone una serie di domande:

  1. A ogni parola magica è associato un ID? Come primo passo nella risoluzione del markup del modulo {{XXX...}}, MediaWiki tenta di tradurre XXX in un ID di ogni parola magica. La tabella di traduzione è definita da $magicWords.
    • Se nessun ID parola magica è associata con XXX, XXX è assunto come un template.

  2. È una variable? Se un ID parola magica è trovata, successivamente MediaWiki controlla per vedere se ha dei parametri.
    • Se nessun parametro viene trovato, MediaWiki controlla se la parola magica ID è stato dichiarato come una variabile ID. Per controllarlo, ricava la lista di parole magiche che servono chiamando MagicWord::getVariableIDs(). Questo metodo ottiene il suo elenco di ID di variabili da un elenco di ID di variabili codificati (vedere Help:Variables ) e da un elenco di ID di variabili personalizzate fornite da tutte le funzioni collegate all'hook MagicWordwgVariableIDs .
      • Se la parola magica ID è stata classificata come una variabile, gli hook MediaWiki chiamano le funzioni associate con l'evento ParserGetVariableValueSwitch fino a che non trova uno che riconosce la parola magica e può ritornare il suo valore

  3. Is it a parser function? If there are any parameters or if the magic word ID is missing from the list of variable magic word IDs, then MediaWiki assumes that the magic word is a parser function or template. If the magic word ID is found in the list of parser functions declared via a call to $wgParser->setFunctionHook($magicWordId, $renderingFunctionName), it is treated as a parser function and rendered using the function named $renderingFunctionName. Otherwise, it is presumed to be a template.

By convention:

  • The magic words called variables are capitalised, case-sensitive and do not have space characters.
  • Parserfunctions are prefixed with a hash sign (#), are case insensitive and do not include space characters.

This is however a convention and one not consistently applied (for historic reasons).

  • Variables do not have space characters, but some translations of variables in other languages DO have spaces
  • Variables generally are capitalised and case-sensitive, but some parser functions also use this convention.
  • Some parser functions start with a hash sign, but some do not.

Where possible you should follow the conventions when defining or translating magic words. Magic words are higher in priority than templates, so any magic word defined, will block the usage of that defined name as a template.

Following the conventions avoids adding more and more potential collisions.

Definire parole magiche

Affinché le parole magiche facciano la loro magia, dobbiamo definire due cose:

  • a mapping between wiki text and a magic word ID
  • a mapping between a magic word ID and some PHP function that interprets the magic word.

Mappatura del testo wiki in ID di parole magiche

The variable $magicWords is used to associate each magic word ID with a language-dependent array that describes all the text strings that mapped to the magic word ID. Importante: questo imposta solo la mappatura i18n di back-end, devi ancora scrivere altro codice per fare in modo che MediaWiki usi la parola magica per qualsiasi cosa Also, make sure that you initialize $magicWords as an empty array before adding language-specific values or you will get errors when trying to load the magic word and will need to rebuild your localization cache before it will work.

l primo elemento di questo array è un flag intero che indica se la parola magica fa distinzione tra maiuscole e minuscole. Gli elementi rimanenti sono un elenco di testo che dovrebbe essere associato alla parola magica ID. Se il flag di distinzione tra maiuscole e minuscole è 0, tutte le varianti maiuscole e minuscole dei nomi nell'array corrisponderanno. Se il flag di distinzione tra maiuscole e minuscole è 1, solo le corrispondenze esatte tra maiuscole e minuscole verranno associate all'ID della parola magica. Thus the format is $magicWords['en'] = [ 'InternalName' => [ 0, 'NameUserTypes', 'AdditionalAliasUserCanType' ] ];

This association is created by $magicWords in a file registered using $wgExtensionMessagesFiles[] .

Nell'esempio seguente, un'installazione di MediaWiki spagnola assocerà la parola magica ID "MAG_CUSTOM" a "personalizado", "custom", "PERSONALIZADO", "CUSTOM" e tutte le altre varianti del caso. In an English MediaWiki only "custom" in various case combinations will be mapped to 'MAG_CUSTOM':

File Example.i18n.magic.php :

<?php

$magicWords = [];

$magicWords['en'] = [
	'MAG_CUSTOM' => [ 0, 'custom' ],
];

$magicWords['es'] = [
	'MAG_CUSTOM' => [ 0, 'personalizado' ],
];

In part of the extension.json file:

"ExtensionMessagesFiles": {
	"ExampleMagic": "Example.i18n.magic.php"
}

Nota che "ExampleMagic" è una chiave diversa dalla chiave che useresti per un semplice file di internazionalizzazione (normalmente solo il titolo dell'estensione, cioè "Esempio"). "Magic" è stato aggiunto deliberatamente in modo che uno non sovrascriva l'altro.

Inline PHP

Puoi associare parole magiche in linea in PHP piuttosto che tramite un file i18n. This is useful when defining hooks in LocalSettings.php but should not be done in extensions.

MediaWiki\MediaWikiServices::getInstance()->getContentLanguage()->mMagicExtensions['wikicodeToHtml'] = ['MAG_CUSTOM', 'custom'];

Associazione di una parola magica ID con una funzione PHP

The mechanism for associating magic word IDs with rendering functions depends on whether the magic word will be used as a parser function or a variable. For more information, please see:

Localizzazione

See Help:Magic words#Localisation for help.

You can read more on definition and usage of magic words for localisation at Manual:Messages API, Manual:Language#Namespaces; Avoid {{SITENAME}} in messages.

Interruttori di comportamento (parole magiche con doppio trattino basso)

Gli interruttori di comportamento sono un tipo speciale di parola magica. Possono essere riconosciuti dal loro uso di doppi trattini bassi (piuttosto che doppie parentesi graffe). Example: __NOTOC__

Queste parole magiche in genere non producono alcun contenuto, ma invece modificano il comportamento di una pagina e / o impostano una proprietà della pagina. These magic words are listed in MagicWordFactory::mDoubleUnderscoreIDs and also at Help:Magic words#Behavior switches. The effect of most standard behavior switches is defined in Parser::handleDoubleUnderscore(). If no specific effect is defined, the magic word will simply set a page property in the page_props table. This can also be checked later by testing if $parser->getOutput()->getPageProperty( 'MAGIC_WORD' ) is null or the empty string

Custom behavior switch

Here is an example extension implementing a custom __CUSTOM__ behaviour switch

custom/extension.json - This is minimal, a real extension would fill out more fields.

{
	"name": "Custom",
	"type": "parserhook",
	"AutoloadClasses": {
		"MyHooks": "MyHooks.php"
	},
	"Hooks": {
		"GetDoubleUnderscoreIDs": [
			"MyHooks::onGetDoubleUnderscoreIDs"
		],
		"ParserAfterParse": [
			"MyHooks::onParserAfterParse"
		]
	},
	"ExtensionMessagesFiles": {
		"CustomMagic": "custom.i18n.php"
	},
	"manifest_version": 1
}

custom/custom.i18n.php

<?php
$magicWords = [];
$magicWords['en'] = [
	'MAG_CUSTOM' => [ 0, '__CUSTOM__' ],
];

custom/MyHooks.php

<?php
class MyHooks {
	public static function onGetDoubleUnderscoreIDs( &$ids ) {
		$ids[] = 'MAG_CUSTOM';
	}

	public static function onParserAfterParse( Parser $parser, &$text, StripState $stripState ) {
		if ( $parser->getOutput()->getPageProperty( 'MAG_CUSTOM' ) !== null ) {
			// Do behavior switching here ...
			// e.g. If you wanted to add some JS, you would do $parser->getOutput()->addModules( 'moduleName' );
		}
	}
}

Vedi anche