Manual:Parser functions/ja

From MediaWiki.org
Jump to: navigation, search
Gnome-preferences-other.svg 拡張機能: 開発 タグの拡張機能 パーサー関数 フック 特別ページ スキン マジックワード API
MediaWiki extensions

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

説明[edit | edit source]

Whereas a Tag extension is expected to take unprocessed text and return HTML to the browser, a parser function can 'interact' with other wiki elements in the page. For example, the output of a parser function could be used as a template parameter or in the construction of a link.

パーサー関数の典型的な構文は以下の通りです:

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

For more information, see the documentation for Parser::setFunctionHook ( $id, $callback, $flags = 0 ). This documentation states:

The callback function should have the form:
function myParserFunction( &$parser, $arg1, $arg2, $arg3 ) { ... }
Or with SFH_OBJECT_ARGS: function myParserFunction( $parser, $frame, $args ) { ... }"

パーサー関数の作成は、タグフックを作成する場合よりも多少込み入っています。 これは、関数名がマジックワードでなければならないためです; マジックワードは、別名および多言語対応をサポートする一種のキーワードです。

単純な例[edit | edit source]

パーサー関数を生成する拡張機能の一例を以下に示します。

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['ExampleExtension'] = __DIR__ . '/ExampleExtension.i18n.php';
 
// Tell MediaWiki that the parser function exists.
function ExampleExtensionSetupParserFunction( &$parser ) {
 
   // Create a function hook associating the "example" magic word with the
   // ExampleExtensionRenderParserFunction() function. See: the section 
   // 'setFunctionHook' below for details.
   $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 = '', $param3 = '' ) {
 
   // The input parameters are wikitext with templates expanded.
   // The output should be wikitext too.
   $output = "param1 is $param1 and param2 is $param2 and param3 is $param3";
 
   return $output;
}

Another file, ExampleExtension.i18n.php, should contain:

<?php
/**
 * @since 1.0.0
 *
 * @file
 *
 * @licence GNU GPL
 * @author Your Name (YourUserName)
 */
 
$magicWords = array();
 
/** English
 * @author Your Name (YourUserName)
 */
$magicWords['en'] = array(
   'example' => array( 0, 'example' ),
);

この機能拡張が有効化されると、以下の記述は

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

以下の出力を生成します:

  • param1 is hello and param2 is hi and param3 is hey

Note: 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.

より長い関数[edit | edit source]

より複雑な関数を記述する場合には、フック関数を _body.php または .hooks.php ファイルに分離し、これらを適当なクラスの静的関数としてもよいでしょう。 この場合、クラスは $wgAutoloadClasses でロードして、フックから静的関数を呼び出すことができます。 例えば:

以下のコードを新しく MyExtension.php ファイルに挿入します:

$wgAutoloadClasses['MyExtensionHooks'] = "$dir/MyExtension.hooks.php";
$wgHooks[' ... '][] = 'MyExtensionHooks::MyExtensionFunction';

次に、以下のコードを新しく MyExtension.hooks.php ファイルに挿入します:

class MyExtensionHooks {
      public static function MyExtensionFunction( ... ) {
           ...
           $parser->setFunctionHook( 'example',
                'MyExtensionHooks::ExampleExtensionRenderParserFunction' );
           ...
      }
}

キャッシュ[edit | edit source]

タグ機能拡張の場合と同様に、動的機能拡張としたい場合は、$parser->disableCache() を使用してキャッシュを無効にできます。

パーサーインターフェイス[edit | edit source]

出力の構文解析の制御[edit | edit source]

作成したパーサー関数が返す Wikitext が完全に構文解析されるようにするには、戻り値の noparse オプションに false をセットします:

return array( $output, 'noparse' => false );

noparse の既定値は、バージョン 1.12 付近のどこかで、 少なくともある状況下において、false から true に変更されたようです。

これを裏返すと、作成したパーサー関数が、Wikitext ではなく、構文解析されない HTML を返すようにするには、以下のように指定します:

return array( $output, 'noparse' => true, 'isHTML' => true );

ところが、

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

の記述は、以下のような出力を生成します:

This is

param1 is hello and param2 is hi and param3 is hey a test.


これは、パーサー関数の HTML 出力に、ハードコードされた "\n\n" 文字列が前置されることが原因です。 この現象を回避するために、HTML コードが周りのテキストに対してインラインとしてレンダリングされるようにするには、以下のように記述します:

return $parser->insertStripItem( $output, $parser->mStripState );

命名規則[edit | edit source]

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.

setFunctionHook フック[edit | edit source]

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 | edit source]

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.

Mixing positional parameters with this named parameter technique is fraught with peril! Your life will be significantly improved if you stick with one or the other.

Your callback function typically looks like this:

function ExampleExtensionRenderParserFunction( $parser, $arg1, $arg2, ..., $argn )

To fake named parameters, simply omit all the arguments after $parser, and pair it with func_num_args(). Here is an example:

function ExampleExtensionRenderParserFunction( $parser ) {
	//Suppose the user invoked the parser function like so:
	//{{#myparserfunction:foo=bar|apple=orange}}
 
	$opts = array();
	// Argument 0 is $parser, so begin iterating at 1
	for ( $i = 1; $i < func_num_args(); $i++ ) {
		$opts[] = func_get_arg( $i );
	}
	//The $opts array now looks like this:
	//	[0] => 'foo=bar'
	//	[1] => 'apple=orange'
 
	//Now we need to transform $opts into a more useful form...
	$options = extractOptions( $opts );
 
	#Continue writing your code...
}
 
/**
 * Converts an array of values in form [0] => "name=value" into a real
 * associative array in form [name] => value
 *
 * @param array string $options
 * @return array $results
 */
function extractOptions( array $options ) {
	$results = array();
 
	foreach ( $options as $option ) {
		$pair = explode( '=', $option, 2 );
		if ( count( $pair ) == 2 ) {
			$name = trim( $pair[0] );
			$value = trim( $pair[1] );
			$results[$name] = $value;
		}
	}
	//Now you've got an array that looks like this:
	//	[foo] => bar
	//	[apple] => orange
 
	return $results;
}

関連項目[edit | edit source]

言語: English  • dansk • Deutsch • Bahasa Indonesia • 日本語 • русский