Hướng dẫn:Từ ma thuật

From mediawiki.org
This page is a translated version of the page Manual:Magic words and the translation is 46% complete.
Outdated translations are marked like this.
Phần mở rộng MediaWiki

Từ ma thuật là một phương pháp để nhóm một số loại các xâu từ wiki thành một ID mà có liên kết với một hàm. Cả biếnhàm tính toán đều sử dụng phương pháp này. Tất cả văn bản được nhóm tới ID đó sẽ được thay thế bằng giá trị trả về của hàm. Ánh xạ giữa các chuỗi văn bản và ID được lưu trữ trong biến $magicWords trong một tệp có thể được tải bằng cách sử dụng $wgExtensionMessagesFiles[] .

Các từ ma thuật mặc định được thực hiện trong CoreParserFunctions.php .

Cách hoạt động của các từ ma thuật(magic words)

Bất cứ khi nào MediaWiki tìm thấy văn bản nằm giữa cặp dấu ngoặc tròn ({{XXX ...}}), nó phải quyết định xem XXX là biến, hàm phân tích cú pháp hay mẫu. Để làm như vậy, nó đặt ra một loạt câu hỏi:

  1. Nó có ID từ ma thuật liên quan không  ? Là bước đầu tiên trong việc giải quyết đánh dấu của biểu mẫu {{XXX...}}, MediaWiki cố gắng dịch XXX sang ID từ ma thuật. Bảng dịch được xác định bởi $magicWords.
    • If no magic word ID is associated with XXX, XXX is presumed to be a template.

  2. Is it a variable? If a magic word ID is found, MediaWiki next checks to see if it has any parameters.
    • If no parameters are found, MediaWiki checks to see if the magic word ID has been declared as a variable ID. To check this, it retrieves the list of magic words serving by calling MagicWord::getVariableIDs(). This method gets its list of variable IDs from a hard coded list of variable IDs (see Help:Variables ) and from a list of custom variable IDs provided by all functions attached to the hook MagicWordwgVariableIDs .
      • If the magic word ID has been classified as a variable, MediaWiki calls the ParserGetVariableValueSwitch function to get the value associated with the variable name.

  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.
Theo quy ước:
  • Các từ magic words(ma thuật) được gọi là biến được viết hoa(chữ cái đầu tiên), phân biệt chữ hoa chữ thường và không có ký tự khoảng trắng.
  • Parserfunctions are prefixed with a hash sign (#), are case insensitive and do not include space characters.

Tuy nhiên, đây là một quy ước và không được áp dụng nhất quán (vì lý do lịch sử).

  • Các biến không có ký tự khoảng trắng, nhưng một số bản dịch của biến trong các ngôn ngữ khác LÀM có khoảng trắng
  • Các biến thường được viết hoa và phân biệt chữ hoa chữ thường, nhưng một số hàm trình phân tích cú pháp cũng sử dụng quy ước này.
  • Một số hàm phân tích cú pháp bắt đầu bằng dấu thăng, nhưng một số thì không.

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.

Định nghĩa các từ ma thuật

Để những từ ma thuật phát huy tác dụng của chúng, chúng ta phải xác định hai điều:

  • ánh xạ giữa văn bản wiki và ID từ ma thuật
  • a mapping between a magic word ID and some PHP function that interprets the magic word.

Liên kết văn bản(text) wiki tới các ID từ ma thuật

Biến $magicWords được sử dụng để kết hợp từng ID từ ma thuật với một mảng phụ thuộc vào ngôn ngữ mô tả tất cả các chuỗi văn bản được ánh xạ tới ID từ ma thuật. Quan trọng: Thao tác này chỉ thiết lập ánh xạ i18n mặt sau, bạn vẫn phải viết mã khác để khiến MediaWiki sử dụng từ kỳ diệu cho mọi thứ. 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.

Phần tử đầu tiên của mảng này là một cờ(flag) số nguyên chỉ ra kiểu(types) của từ mà thuật này. Các phần tử còn lại là chuỗi văn bản được liên kết với ID từ ma thuật. Nếu cờ(flag) phân biệt chữ hoa chữ thường là 0, mọi biến thể chữ hoa chữ thường của các tên trong mảng sẽ liên kết với ID từ ma thuật. Nếu trong trường hợp cờ(flag) chỉ báo là 1 , thì chỉ những trường hợp khớp chính xác mới được liên kết với ID từ ma thuật. Do đó, định dạng là $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:

Địa phương hoá

Xem Help:Magic words#Localisation để thêm trợ giúp

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

Công tắc chuyển hành vi (các từ ma thuật kép được gạch chân)

Công tắc chuyển hành vi là một loại từ ma thuật đặc biệt. Chúng có thể được nhận ra bằng cách sử dụng dấu gạch dưới kép (thay vì dấu ngoặc kép). Ví dụ __NOTOC__. Example: __NOTOC__

Những từ ma thuật này thường không thêm bất kỳ nội dung nào, nhưng lại thay đổi cách mà trang được thể hiện hay đặt thuộc tính của trang. 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' );
		}
	}
}

Xem thêm