Manual:Parser functions

From MediaWiki.org
Jump to: navigation, search
Gnome-preferences-other.svg Extensions: Tag Extensions Parser Functions Hooks Special Pages Skins Magic Words
MediaWiki extensions

Parser functions, added in MediaWiki 1.7, are a type of extension that integrate closely with the parser. The term "parser function" should not be confused with Extension:ParserFunctions, which is a collection of simple parser functions.

Contents

[edit] Description

Tag extensions are expected to take unprocessed text and return HTML; they have very little integration with the rest of the parser. For example, the output of a tag extension cannot be used as a template parameter. Also, expanding templates within a tag extension is possible, but it must be done manually — an error-prone process that changes from version to version.

The typical syntax for a parser function is:

{{ #functionname: param1 | param2 | param3 }}

Creating a parser function is slightly more complicated than creating a new tag because the function name must be a magic word — a keyword that supports aliases and localization.

[edit] Simple example

Below is an example of an extension that creates a parser function.

This file should be called ExampleExtension.php if the name of your extension is ExampleExtension:

<?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',
 
   // Alternatively, you can specify a message key for the description.
   'descriptionmsg' => 'exampleextension-desc',
 
   // 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' => 'https://www.mediawiki.org/wiki/Manual:Parser_functions',
 
);
 
// Specify the function that will initialize the parser function.
$wgHooks['ParserFirstCallInit'][] = 'ExampleExtensionSetupParserFunction';
 
// Allow translation of the parser function name
$wgExtensionMessagesFiles['ExampleExtensionMagic'] = dirname( __FILE__ ) . '/ExampleExtension.i18n.magic.php';
 
// Tell MediaWiki that the parser function exists.
function ExampleExtensionSetupParserFunction( &$parser ) {
 
   // Create a function hook associating the "example" magic word with the
   // ExampleExtensionRenderParserFunction() function.
   $parser->setFunctionHook( 'example', 'ExampleExtensionRenderParserFunction' );
 
   // Return true so that MediaWiki continues to load extensions.
   return true;
}
 
// Render the output of the parser function.
function ExampleExtensionRenderParserFunction( $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;
}

Another file, ExtensionName.i18n.magic.php, should contain:

/**
 * Internationalization file for magic words.
 */
 
$magicWords = array();
 
$magicWords['en'] = array(
   'example' => array( 0, 'example' ),
);

With this extension enabled,

  • {{#example: hello | hi}}

produces:

  • param1 is hello and param2 is hi

[edit] 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 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( ... ) { ... }
}

[edit] Caching

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

[edit] Parser interface

[edit] 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:

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

[edit] 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., {{#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] See also

Language: English  • Bahasa Indonesia • 日本語 • Русский
Personal tools
Namespaces

Variants
Actions
Navigation
Support
Download
Development
Communication
Print/export
Toolbox