Jump to content

Manual:Magiska ord

From mediawiki.org
This page is a translated version of the page Manual:Magic words and the translation is 27% complete.
Outdated translations are marked like this.
MediaWiki-tillägg
This manual is not intended for end users of MediaWiki. Looking for a list of magic words? See Help:Magiska ord . If you are looking for documentation to help you use MediaWiki, read the MediaWiki Handbook .

Magic words are strings of text that MediaWiki links to specific functions or return values, such as current date and time, page titles, site information, and more. They can be thought of as special commands or variables that allow dynamic content generation and interaction with the MediaWiki software during page rendering.

From a technical standpoint, magic words map a range of wiki text strings to a unique internal identifier (ID), which is then associated with a particular function. This ID directs MediaWiki to execute a corresponding operation or return a specific value. Both variables (which output dynamic values) and parser functions (which perform operations or conditional logic) make use of this mapping technique.

All text som leder till detta ID kommer bytas ut mot funktionens returvärde. Kartläggningen mellan textsträngarna och ID:t lagras i variabeln $magicWords i en fil som kan laddas med $wgExtensionMessagesFiles[] .

De förinställda magiska orden implementeras i CoreParserFunctions.php .

Hur magiska ord fungerar

Närhelst MediaWiki hittar text mellan dubbla klammerparenteser ({{XXX ...}}) måste den bestämma om XXX är en variabel, parser-funktion, eller mall. För att göra det, ställer den ett antal frågor:

  1. Finns det ett associerat ID för ett magiskt ord? Som ett första steg i att lösa texten i formatet {{XXX...}}, försöker MediaWiki översätta XXX till ett ID för ett magiskt ord. Översättningstabellen definieras av $magicWords.
    • Finns det inget ID för ett magiskt ord associerat med XXX, antas XXX vara en mall.

  2. Är det en variabel? Om ett ID för ett magiskt ord hittas kommer MediaWikis nästa kontroller att se om den har några parametrar.
    • Hittas inga parametrar, kontrollerar MediaWiki om det magiska ordets ID har förklarats som en variabel-ID. För att kontrollera detta, hämtar den en lista över magiska ord genom att kalla på MagicWord::getVariableIDs(). Denna metod hämtar en lista över variabel-ID:er från en hårdkodad lista över variabel-ID:er (se Help:Variables ) och från en lista över anpassade variabel-ID:er som alla funktioner tillhandahåller, klistrade till haken MagicWordwgVariableIDs .
      • Har det magiska ordet klassificerats som en variabel, kallar MediaWiki funktioner som associeras med eventnamnet ParserGetVariableValueSwitch tills den hittar en som känner igen det magiska ordet och kan returnera dess värde.

  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 declared parser functions, it is treated as a parser function and rendered using the function named $renderingFunctionName. Otherwise, it is presumed to be a template.

Definiera magiska ord

When defining or translating magic words, adhere to established conventions.

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 spaces in English, 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 the conventions for defining or translating magic words should be followed. 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 creating additional potential naming collisions.

For magic words to do their magic we must define two things:

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

Mapping wiki text to magic word IDs

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. Important: This only sets up the back end i18n mapping, you still have to write other code to make MediaWiki use the magic word for anything. 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.

The first element of this array is an integer flag indicating whether or not the magic word is case sensitive. The remaining elements are a list of text that should be associated with the magic word ID. If the case sensitive flag is 0, any case variant of the names in the array will match. If the case sensitive flag is 1, only exact case matches will be associated with the magic word ID. Thus the format is $magicWords['en'] = [ 'InternalName' => [ 0, 'NameUserTypes', 'AdditionalAliasUserCanType' ] ];

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

In the example below, a Spanish MediaWiki installation will associate the magic word ID 'MAG_CUSTOM' with "personalizado", "custom", "PERSONALIZADO", "CUSTOM" and all other case variants. 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"
}

Note that "ExampleMagic" is a different to the key you would use for a plain internationalization file (normally just the title of the extension, i.e. "Example"). "Magic" has been appended deliberately so one does not overwrite the other.

In inline PHP

You can associate magic words inline in PHP rather than through a i18n file. 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'];

Associating a magic word ID with a PHP function

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:

Lokalisering

Läs Help:Magic words#Localisation för hjälp.

Du kan läsa mer om definiering och användning av magiska ord för lokalisering på [[Manual:Messages API |Manual:Meddelanden-API]], Manual:Språk#Namnrymder; Undvik {{SITENAME}} i meddelanden.

Behavior switches (double underscore magic words)

Behavior switches are a special type of magic word. They can be recognized by their use of double underscores (rather than double braces). Example: __NOTOC__

These magic words typically do not output any content, but instead change the behavior of a page and/or set a page property. 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

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

{
	"name": "MyExt",
	"type": "parserhook",
    "AutoloadNamespaces": {
		"MediaWiki\\Extension\\MyExt\\": "includes/"
	},
	"Hooks": {
		"GetDoubleUnderscoreIDs": "main",
		"ParserAfterParse": "main" 
	},
	"HookHandlers": {
		"main": {
			"class": "MediaWiki\\Extension\\MyExt\\Hooks",
			"services": [ "MainConfig" ]
		}
	},
	"ExtensionMessagesFiles": {
		"MyExtMagic": "custom.i18n.magic.php"
	},
	"manifest_version": 2
}

MyExt/MyExt.i18n.magic.php

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

MyExt/includes/Hooks.php

<?php
namespace MediaWiki\Extension\MyExt;
class Hooks implements GetDoubleUnderscoreIDsHook, ParserAfterParseHook {
	public function onGetDoubleUnderscoreIDs( &$ids ) {
		$ids[] = 'MAG_CUSTOM';
	}

	public function onParserAfterParse( $parser, &$text, $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' ] );
		}
	}
}


Se även