Pedoman:Fungsi parser

From MediaWiki.org
Jump to navigation Jump to search
This page is a translated version of the page Manual:Parser functions and the translation is 23% complete.
Outdated translations are marked like this.
Other languages:
Bahasa Indonesia • ‎Deutsch • ‎English • ‎Tiếng Việt • ‎dansk • ‎español • ‎français • ‎polski • ‎português do Brasil • ‎русский • ‎ไทย • ‎中文 • ‎日本語 • ‎한국어
OOjs UI icon puzzle-ltr.svg Extensions: Pengembangan Tag extensions Pedoman:Fungsi parser Hooks Special pages Kulit Petunjuk: Kata pencarian API Content models
MediaWiki extensions

Fungsi parser, yang ditambahkan pada MediaWiki 1.7, adalah sejenis ekstensi (penjabaran) yang melakukan integrasi tertutup dengan menggunakan parser. Istilah "fungsi parser" tidak sama dengan Extension:ParserFunctions , yang merupakan kumpulan fungsi parser sederhana. (Lihat Help:Extension:ParserFunctions untuk itu)

Deskripsi

Jika sebuah ekstensi tag dimaksudkan untuk menyulap teks menjadi HTML ke sebuah alat penjelajah, adapun fungsi parser bisa 'bersahabat' dengan elemen wiki lainnya pada halaman yang sama. Contohnya, keluaran sebuah fungsi parser bisa digunakan sebagai parameter sebuah templat atau di dalam bangunan sebuah pranala.

Sintaks umum untuk sebuah fungsi parser adalah:

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

Untuk informasi lainnya, lihat the documentation mengenai Parser::setFunctionHook ( $id, $callback, $flags = 0 ). Dokumentasi ini menyebutkan:

Fungsi pemanggilan harus menyediakan isian:
function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
Atau dengan SFH_OBJECT_ARGS:
function myParserFunction( $parser, $frame, $args ) { ... }"

Menciptakan sebuah fungsi parser sedikit agak rumit daripada membuat sebuah tag karena nama fungsinya harus berupa kata ajaib, kata kunci yang bisa dibuat aliasnya dan lokalisasinya.

Contoh mudah

Berikut ini adalah contoh ekstensi yang menciptakan sebuah fungsi parser.

Pendaftarannya masuk ke extension.json, kode ke ExampleExtension.class.php:

{
	"name": "ExampleExtension",
	"author": "Me",
	"version": "1.0.0",
	"url": "https://www.mediawiki.org/wiki/Extension:ExampleExtension",
	"descriptionmsg": "exampleextension-desc",
	"license-name": "GPL-2.0-or-later",
	"type": "parserhook",
	"MessagesDirs": {
		"ExampleExtension": [
			"i18n"
		]
	},
	"AutoloadClasses": {
		"ExampleExtensionHooks": "src/ExampleExtensionHooks.php"
	},
	"ExtensionMessagesFiles": {
		"ExampleExtensionMagic": "ExampleExtension.i18n.php"
	},
	"Hooks": {
		"ParserFirstCallInit": "ExampleExtensionHooks::onParserFirstCallInit"
	},
	"manifest_version": 1
}
<?php
class ExampleExtensionHooks {
   // Register any render callbacks with the parser
   public static function onParserFirstCallInit( Parser $parser ) {

      // Create a function hook associating the "example" magic word with renderExample()
      $parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] );
   }

   // Me-render keluaran {{#example:}}
   public static function renderExample( Parser $parser, $param1 = '', $param2 = '', $param3 = '' ) {

      // Parameter-parameter masukan berupa teks wiki dengan templat terbuka.
      // Keluarannya harus berupa teks wiki juga.
      $output = "param1 is $param1 and param2 is $param2 and param3 is $param3";

      return $output;
   }
}

Berkas lainnya, ExampleExtension.i18n.php, harus mengandung:

<?php
/**
 * @license GPL-2.0-or-later
 * @author Your Name (YourUserName)
 */

$magicWords = [];

/** English
 * @author Your Name (YourUserName)
 */
$magicWords['en'] = [
   'example' => [ 0, 'example' ],
];

With this extension enabled,

  • {{#example: hello | hi | hey}}

produces:

  • param1 is hello and param2 is hi and param3 is hey
This magicWords array is not optional. If it is omitted, the parser function simply will not work; the {{#example: hello | hi}} will be rendered as though the extension were not installed.

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 extension.json file:

"Hooks": {
	"ParserFirstCallInit": "ExampleExtensionHooks::onParserFirstCallInit"
},
"AutoloadClasses": {
	"ExampleExtensionHooks": "src/ExampleExtensionHooks.php"
}

Then put this is in your src/ExampleExtensionHooks.php file:

class ExampleExtensionHooks {
      public static function onParserFirstCallInit( Parser $parser ) {
           $parser->setFunctionHook( 'example', [ self::class, 'renderExample' ] );
      }
}

Caching

As with tag extensions, $parser->disableCache() may be used to disable the cache for dynamic extensions. This has a significant negative impact on performance, so only use when necessary.

Parser interface

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 [ $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 [ $output, 'noparse' => true, 'isHTML' => true ];

However,

This is {{#example:hello | hi | hey }} a test.

will produce something like this:

This is

param1 is hello and param2 is hi and param3 is hey 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 );

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.

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

Named parameters

Parser functions do not support named parameters the way templates and tag extensions do, but it is occasionally useful to fake it. Users are often accustomed to using vertical bars ( | ) to separate arguments, so it's nice to be able to do that in the parser function context, too. Here's a simple example of how to accomplish this:

function ExampleExtensionRenderParserFunction( &$parser ) {
	// Suppose the user invoked the parser function like so:
	// {{#myparserfunction: foo=bar | apple=orange | banana }}

	$options = extractOptions( array_slice( func_get_args(), 1 ) );

	// Now you've got an array that looks like this:
	// [foo] => 'bar'
	// [apple] => 'orange'
	// [banana] => true
	// Continue writing your code...
}

/**
 * Converts an array of values in form [0] => "name=value"
 * into a real associative array in form [name] => value
 * If no = is provided, true is assumed like this: [name] => true
 *
 * @param array string $options
 * @return array $results
 */
function extractOptions( array $options ) {
	$results = [];
	foreach ( $options as $option ) {
		$pair = array_map( 'trim', explode( '=', $option, 2 ) );
		if ( count( $pair ) === 2 ) {
			$results[ $pair[0] ] = $pair[1];
		}
		if ( count( $pair ) === 1 ) {
			$results[ $pair[0] ] = true;
		}
	}
	return $results;
}

See also