Manual:Parser functions/ru

Функции анализатора (Parser functions) первоначально были добавлены в MediaWiki 1.7 и являются тесно интегрированным расширением. Не следует путать термин "parser function" с Extension:ParserFunctions, которое содержит простые функции парсера.

Описание
Тег расширения принимает необработанный текст и возвращает HTML; они имеют очень мало интеграции с остальными парсерами. Как пример, вывод из тега расширения не может быть использован в параметре шаблона. Однако, возможен дополнительный шаблон внутри тега, но это должно быть сделано в ручную &mdash; это подверженный ошибкам процесс меняется от версии к версии.

Типичный синтаксис для функции парсера:

Создание функции парсера несколько сложнее, чем создание нового тега, так как имя функции должно быть определено magic word &mdash; ключевым словом, которое поддерживает псевдонимы и локализации.

Простой пример
Ниже приведен пример расширения, которое создает функцию парсера.

Это расширение подключается:



выдавая:


 * param1 is hello and param2 is hi

Longer functions
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  file:

Then put this is in your  file:

Caching
As with tag extensions, $parser->disableCache may be used to disable the cache for dynamic extensions.

Controlling the parsing of output
To have the wikitext returned by your parser function be fully parsed (including expansion of templates), set the noparse option to false when returning: 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:

However, This is 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:

Naming
By default, MW adds a hash character (number sign, "#") to the name of each parser function. To suppress that addition (and obtain a parser function with no "#" prefix), include the SFH_NO_HASH constant in the optional flags argument to setFunctionHook, as described below.

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 is enabled, also avoid function names equal to an interwiki prefix.

The setFunctionHook hook
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.,. The callback function should have the form:

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