Manual:Parser functions/ru
![]() |
Расширения тегов | Функции парсера | Обработчики (hooks) | Служебные страницы | Стили оформления (skins) | Волшебные слова |
Функции анализатора (Parser functions) первоначально были добавлены в MediaWiki 1.7 и являются тесно интегрированным расширением. Не следует путать термин "parser function" с Extension:ParserFunctions/ru, которое содержит простые функции парсера.
Contents |
Описание[edit]
Тег расширения принимает необработанный текст и возвращает HTML; они имеют очень мало интеграции с остальными парсерами. Как пример, вывод из тега расширения не может быть использован в параметре шаблона. Однако, возможен дополнительный шаблон внутри тега, но это должно быть сделано в ручную — это подверженный ошибкам процесс меняется от версии к версии.
Типичный синтаксис для функции парсера:
{{ #functionname: param1 | param2 | param3 }}
Создание функции парсера несколько сложнее, чем создание нового тега, так как имя функции должно быть определено magic word — ключевым словом, которое поддерживает псевдонимы и локализации.
Простой пример[edit]
Ниже приведен пример расширения, которое создает функцию парсера.
<?php // Take credit for your work. $wgExtensionCredits['parserhook'][] = array( // The full path and filename of the file. This allows MediaWiki // to display the Subversion revision number on Special:Version. 'path' => __FILE__, // The name of the extension, which will appear on Special:Version. 'name' => "Example Parser Function", // A description of the extension, which will appear on Special:Version. 'description' => "A simple example parser function extension", // The version of the extension, which will appear on Special:Version. // This can be a number or a string. 'version' => 1, // Your name, which will appear on Special:Version. 'author' => "Me", // The URL to a wiki page/web page with information about the extension, // which will appear on Special:Version. 'url' => "http://www.mediawiki.org/wiki/Manual:Parser_functions" ); // Specify the function that will initialize the parser function. $wgHooks['ParserFirstCallInit'][] = 'efExampleParserFunction_Initialize'; // Specify the function that will register the magic words for the parser function. $wgHooks['LanguageGetMagic'][] = 'efExampleParserFunction_RegisterMagicWords'; // Tell MediaWiki that the parser function exists. function efExampleParserFunction_Initialize(&$parser) { // Create a function hook associating the "example" magic word with the // efExampleParserFunction_Render() function. $parser->setFunctionHook('example', 'efExampleParserFunction_Render'); // Return true so that MediaWiki continues to load extensions. return true; } // Tell MediaWiki which magic words can invoke the parser function. function efExampleParserFunction_RegisterMagicWords(&$magicWords, $langCode) { // Add the magic words. // If the first element of the array is 0, the magic word is case insensitive. // If the first element of the array is 1, the magic word is case sensitive. // The remaining elements in the array are "synonyms" for the magic word. $magicWords['example'] = array(0, 'example'); // Return true so that MediaWiki continues to load extensions. return true; } // Render the output of the parser function. function efExampleParserFunction_Render($parser, $param1 = '', $param2 = '') { // The input parameters are wikitext with templates expanded. // The output should be wikitext too. $output = "param1 is $param1 and param2 is $param2"; return $output; }
Это расширение подключается:
- {{#example: hello | hi}}
выдавая:
- param1 is hello and param2 is hi
Longer functions[edit]
For longer functions, you may want to split the hook functions out to a _body.php or .hooks.php file and make them static functions of a class. Then you can load the class with $wgAutoloadClasses and call the static functions in the hooks, e.g.:
Put this in your MyExtension.php
file:
$wgAutoloadClasses['MyExtensionHooks'] = "$dir/MyExtension.hooks.php"; $wgHooks[' ... '][] = 'MyExtensionHooks::MyExtensionFunction';
Then put this is in your MyExtension.hooks.php
file:
class MyExtensionHooks { public static function MyExtensionFunction( ... ) { ... } }
Caching[edit]
As with tag extensions, $parser->disableCache() may be used to disable the cache for dynamic extensions.
Parser interface[edit]
Controlling the parsing of output[edit]
To have the wikitext returned by your parser function be fully parsed (including expansion of templates), set the noparse option to false when returning:
return array( $output, 'noparse' => false );
It seems the default value for noparse changed from false to true, at least in some situations, sometime around version 1.12.
Conversely, to have your parser function return HTML that remains unparsed, rather than returning wikitext, use this:
return array( $output, 'noparse' => true, 'isHTML' => true );
However,
This is {{#example:hello | hi }} a test.
will produce something like this:
This is
param1 is hello and param2 is hi a test.
This happens due to a hardcoded "\n\n" that is prepended to the HTML output of parser functions. To avoid that and make sure the HTML code is rendered inline to the surrounding text, you can use this:
return $parser->insertStripItem( $output, $parser->mStripState );
Именование[edit]
По-умолчанию, MW добавляет хеш-символ (знак номера, "#") в имя каждой функции парсера. Для подавления добавления (и получить функцию парсера без символа "#"), включите константу SFH_NO_HASH в дополнительные аргументы setFunctionHook, как описано ниже.
When choosing a name without a hash prefix, note that transclusion of a page with a name starting with that function name followed by a colon is no longer possible. In particular, avoid function names equal to a namespace name. In the case that interwiki transclusion [1] is enabled, also avoid function names equal to an interwiki prefix.
The setFunctionHook hook[edit]
For more details of the interface into the parser, see the documentation for setFunctionHook in includes/Parser.php. Here's a (possibly dated) copy of those comments:
function setFunctionHook( $id, $callback, $flags = 0 )
Parameters:
- string $id - The magic word ID
- mixed $callback - The callback function (and object) to use
- integer $flags - Optional, set it to the SFH_NO_HASH constant to call the function without "#".
Return value: The old callback function for this name, if any
Create a function, e.g., {{#sum:1|2|3}}
. The callback function should have the form:
function myParserFunction( $parser, $arg1, $arg2, $arg3 ) { ... }
The callback may either return the text result of the function, or an array with the text in element 0, and a number of flags in the other elements. The names of the flags are specified in the keys. Valid flags are:
- found
- The text returned is valid, stop processing the template. This is on by default.
- nowiki
- Wiki markup in the return value should be escaped
- noparse
- Unsafe HTML tags should not be stripped, etc.
- noargs
- Don't replace triple-brace arguments in the return value
- isHTML
- The returned text is HTML, armour it against wikitext transformation
См. также[edit]
- Manual:Extensions/ru
- Manual:Tag extensions
- Manual:Magic words
- Manual:Parser.php
- Extensions FAQ
- Help:Extension:ParserFunctions
- Расширение ParserFunctions — широко известная коллекция функций парсера.
Язык: | English • dansk • Deutsch • Bahasa Indonesia • 日本語 • русский |
---|