Jump to content

Manual:メッセージAPI

From mediawiki.org
This page is a translated version of the page Manual:Messages API and the translation is 28% complete.
国際化の説明文書

MediaWiki のメッセージ は、Message クラスやそれに関するメソッドを介してコードで使用できます。

メッセージのパラメーター

一部のメッセージにはパラメーターがあります。 これらは、(静的) メッセージ テキストで $1$2$3、… で表され、実行時に置換されます。 典型的なパラメーター値には、数字 (「3」の場合、「3つのバージョンを削除しますか?」)、利用者名 (「Bob」の場合、「ページ最終編集者 Bob」)、ページ名、リンクなどがあります。また、別のメッセージの場合もあります。 パラメーターは任意の複雑さを持てます。

特定のメッセージそれぞれに定義されたパラメーターのリストは、MediaWiki の「languages/」フォルダー内の特別なファイル「qqq.json」に配置されます。詳細は説明文書を参照してください。

PLURAL、GENDER、GRAMMAR のマジックワードを使用することをお勧めします。 例えば、{{PLURAL:$1|subpage|subpages}} は、sub{{PLURAL:$1|page|pages}} よりも優れています。 これは検索がより容易になるからです。

他のメッセージを参照する

メッセージ内で下位メッセージを参照すると便利な場合があります。例えば、「X ボタンを使用」や「Y ページを訪問」というフレーズでは、翻訳が一貫していることを保証するために使用されます。 これを行うには、以下の構文を使用できます:

  • {{int:X}} – インターフェイス言語で下位メッセージを使用する。 これは、フォーム ボタンやサイト ナビゲーションなどを参照する場合によく使用されます。例: showpreview
  • {{MediaWiki:Y}} – コンテンツ言語で下位メッセージを使用する。 これは、下位メッセージがローカル ページの翻訳可能な名前を定義する場合に使用されます。例: mainpagegrouppage-sysoppolicy-url など。
  • {{#Special:Z}} – コンテンツ言語で特別ページの名前を使用する。

より複雑なものが必要な場合 (例: 使用される下位メッセージが構成に依存する場合)、コードで解析して、下位メッセージ全体をパラメーターとして渡します。

例:

Before saving, use the {{int:foo-test}} button to test the changes. Visit [[{{MediaWiki:foo-help}}|the help page]] to learn more.Customize this feature at [[{{#Special:Preferences}}]].

メッセージ内の分岐…

パラメーターの値によって、メッセージの正確な言い回しや文法的なバリエーションが影響する場合があります。 私たちが「$1 (sub)page(s) of his/her userpage」のような醜い構造物に頼らないのは、これらが利用者にとって不親切で、より良い方法があるからです。 代わりに、実行時に既知の値に従って解析されるスイッチを作成します。 その後、静的なメッセージ テキストは、可能な選択肢のそれぞれをリストで提供し、スイッチの名前と、違いを生む値への参照が前に付けられます。 これは、MediaWiki で パーサー関数 が呼び出される方法に似ています。 いくつかの種類のスイッチを利用できます。 これらは、メッセージの完全な解析、または {{ 変換の場合にのみ機能します。

...数値でのPLURALの使用

MediaWiki は複数形をサポートしており、より見栄えの良い表示が可能になります。 例:

'undelete_short' => 'Undelete {{PLURAL:$1|one edit|$1 edits}}',

特定の数値に対して明示的な複数形を指定したい場合は、以下の構文を使用できます:

'Box has {{PLURAL:$1|one egg|$1 eggs|12=a dozen eggs}}.'

すべての数値に対する PLURAL の使用に注意

メッセージ本文に数値を挿入する場合、その数値が常に 1 より大きくても、言語によっては PLURAL を使用する必要があることに注意してください。 その理由は、英語以外の言語における PLURAL は非常に異なる複雑な区別を生じることがあり注意が必要だからです (英語で 1st, 2nd, 3rd, 4th, … 11th, 12th, 13th, … 21st, 22nd, 23rd, … などの区別があるのと同様です)。

「no items counted」「one item counted」「more items counted」のように、3 つの異なるメッセージを用意しようとしないでください。 むしろ、1 つのメッセージでまとめ、各言語の翻訳者と PLURAL に任せて、それぞれの言語で表示上の違いが適切に処理されるようにしてください。

可能であれば、常に数値をパラメーターとして含めてください。 可能であれば、英語では意味が通らなくても、常に {{PLURAL:}} 構文を元のメッセージに追加してください。 この構文は翻訳者の参考になります。

小数もサポートされていますが、複数形の規則は完全ではない場合があります。

リストに関するメッセージにはリスト項目の数をパラメーターとして渡す

単数形と複数形だけがあるとは限らないことに注意してください。 多くの言語では 2 つ以上の形があり、実際の数に応じて異なります。そのため、リストで読者に見える項目を表現する際には、リスト項目の数に応じて文法を使い分ける必要があります。 したがって、コードでリストを生成する際には、件数が英語で使われない場合でも、リストに関する見出し、導入文、フッターやその他のメッセージに count( $list ) をパラメーターとして必ず渡してください。 不可視のリストについて中立的に表現する方法があるため、事前に項目数を数えることなく、別ページ上のリストへのリンクを設けられます。

…on user names via GENDER


'foobar-edit-review' => 'Please review {{GENDER:$1|his|her|their}} edits.'

メッセージ内で利用者を参照する場合は、利用者名をメッセージのパラメーターとして渡し、メッセージの説明文には性別対応があることを追記してください。 GENDER が性別変化のある言語への翻訳で使われる可能性がある場合は、英語の原文メッセージにも明示的に追加してください。

現在ログイン中の利用者に直接呼びかける場合は、利用者名のパラメーターを空のままにしてください:

'foobar-logged-in-user' => 'You said {{GENDER:|you were male|you were female|nothing about your gender}}.'
MediaWiki バージョン:
1.31
Gerrit change 398772

メッセージに利用者名 (例:「$1 があなたに感謝を示しました。」) を含める場合は、まず wfEscapeWikitext() を通して渡すことを検討してください。これにより、*; のような文字が誤って解釈されるのを防げます。

Users have grammatical genders

メッセージが利用者に言及する場合、利用者に関連する場合、または利用者に直接呼びかける場合には、利用者名をパラメーターとしてメッセージに渡す必要があります。 こうすることで、性別に応じた適切な文法を使用する必要がある言語や、使用したい言語でも対応できるようになります。 これは、メッセージに利用者名を表示するつもりがない場合でも行うべきです。例えば「inform the user on his/her talk page」(利用者に利用者の会話ページで通知する) といった場合も、英語では「inform the user on {{GENDER:$1|his|her|their}} talk page」とする方が適切です。

これは、メッセージの文言を「性別に基づいて」表現することを推奨するという意味ではありません。明確かつ正確に可能な場合は、必ず性別に依存しない言葉を使用してください。

…on use context inside sentences via GRAMMAR

Grammatical transformations for agglutinative language (Q171263) is also available. For example for Finnish, where it was an absolute necessity to make language files site-independent, i.e. to remove the Wikipedia references. In Finnish, "about Wikipedia" becomes "Tietoja Wikipediasta" and "you can upload it to Wikipedia" becomes "Voit tallentaa tiedoston Wikipediaan". Suffixes are added depending on how the word is used, plus minor modifications to the base. There is a long list of exceptions, but since only a few words needed to be translated, such as the site name, we didn't need to include it.

MediaWiki has grammatical transformation functions for over 20 languages. Some of these are just dictionaries for Wikimedia site names, but others have simple algorithms which will fail for all but the most common cases.

Even before MediaWiki had arbitrary grammatical transformation, it had a nominative/genitive distinction for month names. This distinction is necessary for some languages if you wish to substitute month names into sentences.

Filtering special characters in parameters and messages

The other (much simpler) issue with parameter substitution is HTML escaping. Despite being much simpler, MediaWiki does a pretty poor job of it.

PHP でのメッセージの使用

警告 警告: 必ず下記のうちいずれかの出力モードを使用してください

簡単な例を示します:

$out = Xml::submitButton( wfMessage( 'submit' )->text() );

wfMessage() は、Message クラスのラッパーとして機能し、Message オブジェクトを作成するグローバル関数です。 This example then invokes Message method text() which fetches the text of the submit message in the current language, performs certain language transformations (such as gender and plural), and returns the unescaped message text.

Here is a more complex example using a message that takes a count and supports linguistic plural handling:

$out = Xml::label( wfMessage( 'numberofpages' )->numParams( $count )->text() );

Don't use the formatnum magic word in messages. Always format the numbers in code.

The following sections explain the code.

パラメーター

Given a message like the following:

{
    "msg": "Values are $1, $2"
}

You pass parameters to messages that need them in several ways:

wfMessage( 'msg', 'param1', 'param2' )->plain();
wfMessage( 'msg' )->params( 'param1', 'param2' )->plain();
wfMessage( 'msg', [ 'param1', 'param2' ] )->plain();

The first approach is most common, use the second approach when mixing different types of parameters, and you can use the third to construct message objects dynamically from other data. There are different types of parameters:

wfMessage( 'msg' )->params( $username )->plain();
wfMessage( 'msg' )->rawParams( $link )->plain();
wfMessage( 'msg' )->plaintextParams( $userInput )->plain();

wfMessage( 'msg' )->numParams( $count )->plain();
wfMessage( 'msg' )->durationParams( $duration )->plain(); // MediaWiki 1.22+
wfMessage( 'msg' )->expiryParams( $expiry )->plain(); // MediaWiki 1.22+
wfMessage( 'msg' )->timeperiodParams( $period )->plain(); // MediaWiki 1.22+
wfMessage( 'msg' )->sizeParams( $size )->plain(); // MediaWiki 1.22+
wfMessage( 'msg' )->bitrateParams( $bitrate )->plain(); // MediaWiki 1.22+
params()
Normal message substitution parameter.
rawParams()
Substitutes the parameter after the message has been otherwise processed; this means that these parameters are not available to parser functions, nor are they escaped if escaping output format is used (see below). Make sure you escape them properly yourself.
plaintextParams()
Like rawParams(), but does escaping. It is useful when you pass user input that may contain wikitext that should not be parsed.

Each function from the second group formats the value in a specific way before the substitution. numParams() must be used if the message uses {{PLURAL:}}. In some cases you might not want to use it even though you have a number, for example a revision ID. The other functions correspond to Language functions formatDuration, formatExpiry, formatTimePeriod, formatSize and formatBitrate, and are just shorthands for calling them directly.

言語

To override the language in which you want the message, there is one method and one shortcut for the common case of using wiki content language. In the latter case you can use either a language code or a language object. The usual language fallback chains apply, so the actual message you get may be in a different language than requested, if a translation does not exist.

wfMessage( 'message-key' )->inContentLanguage();
wfMessage( 'message-key' )->inLanguage( $lang );

Output modes and escaping

The Message class, and thus the object returned by wfMessage(), has five output modes:

  • plain()returns the message text as-is; only parameters are substituted[1]
  • text()transforms the message text (see MessageCache::transform()) which transforms all {{}} including templates and parser functions like PLURAL and GENDER, but neither escapes nor sanitizes
  • escaped()same as 'text', but also escapes it for use in HTML
  • parse()parses the message text from wikitext to HTML and sanitizes (MessageCache::parse() which calls the Parser)
  • parseAsBlock()the output is wrapped in a block level HTML element, if not already, similarly to OutputPage::addWikiMsg

Remember that Html:: functions escape everything fed into them, so use the text() format with those to avoid double escaping. Hence the most common output format is text(). Also, make sure to use parse() or parseAsBlock() if the message has wikitext in it, otherwise the wikitext will just be escaped and output as plain text.

When using wfMessage() or $this->msg(), you should always specify an output type. text() is appropriate when you're outputting it through addWikiText().

Which output mode to use

Generally speaking, the most common modes you will use are ->parse() and ->text(). You use ->parse() in most places where HTML markup is supported, and you use ->text() in places where the content is going to become HTML escaped or HTML markup is not supported.

Some common cases:

  • If you are putting the message in the text part (third argument) of Html::element use ->text(). You may also consider using Html::rawElement() instead and using the ->parse() mode.
  • If you are putting in text (third argument) of Html::rawElement(), you should generally use ->parse().
  • If you are putting into the attributes (second argument) of Html::rawElement() or Html::element(), use ->parse()
  • If you are manually constructing HTML attributes, you should use ->escaped(). However you should never manually construct HTML attributes
  • For $out->addWikiText() where $out is an OutputPage object use ->text() or ->plain(). However consider if you would rather use $out->addWikiMsg instead.
  • For $out->addHTML() use ->parse()

Method chaining

Most Message methods return the current object, so you can conveniently call one after another to operate on an object before finally returning its text. This is called method chaining. Here is an example:

wfMessage( 'key' )
	->params( 'apple' )
	->numParams( $numOfApples )
	->setContext( $context )
	->inContentLanguage()
	->parse()

Additional methods of printing messages

The general message function in MediaWiki is wfMessage. However, since in a message the value of magic words can depend on the context, there are various wrappers to this function, that automatically set the correct context.

OutputPage has a few methods that append directly to the generated output. The useful ones are:

$out->addWikiMsg( 'pageheader' );
$out->wrapWikiMsg( '<div class="error">\n$1\n</div>', [ 'someerrormessage', $user->getName() ] );

Both of the above parse the wikitext in the context of the current page before appending it to output buffer.

Classes extending ContextSource have a method msg that automatically sets the current context (language, current page etc.). It is therefore recommended to use $this->msg() for those classes, like special pages. Here is a non-exhaustive list of such classes:[2]

  • CategoryViewer
  • HTMLForm
  • LogEventsList
  • DifferenceEngine
  • OutputPage
  • IndexPager
  • ImageHistoryList
  • ApiBase
  • ChangesList
  • Skin
警告 警告: The QuickTemplate class and its subclasses (BaseTemplate) have a method named msg which is different from the one from ContextSource. In these classes $this->msg() will simply output the escaped text of the message.

Examples of correct usage:

wfMessage( 'key' )->numParams( 567 )->text();
$this->msg( 'key' )->numParams( 567 )->parse();

Examples of incorrect usage:

wfMessage( 'key', 345 )->parseInline(); # Number is not formatted correctly
$this->msg( 'key', 345 )->numParams( 234 )->plain() # Plural syntax is not converted in plain format

Using messages in JavaScript

This page only deals with MediaWiki core. See the specific documentation instead for the jquery.i18n module.

Getting the messages to the client

To use the messages, we need to make sure that the messages are available at client side first. This can be done using either a ResourceLoader module (most common) or an API query from JavaScript (rare).

Using a ResourceLoader module

This is the most common method of delivering messages. You should use this unless you have a good reason not to.

We are going to use ResourceLoader to make sure that the messages are available at the client side. For this, in your ResourceLoader modules, define the messages to be exported to the client side.

If you plan to use the mw.message(…).parse() to generate HTML from wikitext in interface messages, then it is important to load the mediawiki.jqueryMsg module.

例 (extension.json):

{
	"ResourceModules": {
		"ext.abuseFilter.edit": {
			"scripts": "ext.abuseFilter.edit.js",
			"messages": [
				"abusefilter-edit-syntaxok",
				"abusefilter-edit-syntaxerr",
				"abusefilter-http-error",
				"abusefilter-edit-throttle-placeholder",
				"abusefilter-edit-tag-placeholder",
				"abusefilter-edit-warn-leave",
				"unknown-error",
				"jan",
				"feb",
				"mar"
			],
			"dependencies": [
				"mediawiki.util",
				"mediawiki.api",
				"mediawiki.confirmCloseWindow",
				"jquery.textSelection",
				"jquery.spinner",
				"oojs-ui-core",
				"oojs-ui-widgets"
			]
		}
	}
}

Using an API query from JavaScript

This is not a common way of loading messages. You should only use this if there is a good reason why you can't use the ResourceLoader module method above.

You can use the following code:

MediaWiki バージョン:
1.27
// When: The 'mediawiki.api' module is loaded, and, the page is ready
$.when( mw.loader.using( [ 'mediawiki.api', 'mediawiki.jqueryMsg' ] ), $.ready )
    // Then: Load the messages that you need (if they are not yet loaded)
    .then( () => new mw.Api().loadMessagesIfMissing( [ 'january', 'february', 'march' ] ) )
    // Then: Do stuff with them
    .then( doStuff );

To get the messages in some language other than the UserLanguage language, use getMessages instead of loadMessagesIfMissing, and supply the target language as the "amlang" field of the optional second parameter, like so:

// When: The 'mediawiki.api' module is loaded. No need to wait for the page to be ready.
$.when( mw.loader.using( [ 'mediawiki.api' ] ) )
    // Then: get some messages in French (language code 'fr')
    .then( () => new mw.Api().getMessages( [ 'january', 'february', 'march' ], { amlang: 'fr' } ) )
    // Then: Do stuff with them
    .then( doStuff );
// doStuff is a function that will receive as its first parameter an object that looks like so:
// { february: "février", january: "janvier", march: "mars" }

Use of the messages

The messages defined in the above example will be available at client side and can be accessed by mw.message( 'message-key-name' ).

例:

$( '<div>' ).text( mw.message( 'translate-msggroupselector-projects' ).text() );

Note how we use jQuery text method to escape our output properly when using mw.message text format.

If your message contains wikitext formatting, you can instead use the following:

$( '<div>' ).append( mw.message( 'translate-msggroupselector-projects' ).parseDom() );

Here we use jQuery append method to insert the DOM nodes returned by mw.message parseDom format.

In older code you might also encounter the following: (parseDom was not available until MediaWiki 1.27)

$( '<div>' ).html( mw.message( 'translate-msggroupselector-projects' ).escaped() );
$( '<div>' ).html( mw.message( 'translate-msggroupselector-projects' ).parse() );

There are other correct combinations, but whenever possible, stick to the patterns above to avoid XSS vulnerabilities and make your code easier to understand for others.

We can also pass the dynamic parameters to the message (i.e. the values for $1, $2, etc.) as shown below.

$( '<div>' ).text( mw.message( 'hello-user', username ).text() );

In the above examples, note that the message should be defined in an i18n file. メッセージ キーがどの i18n ファイルにも見つからない場合、結果は曲線山括弧 U+29FC/U+29FD (数学記号の一部) で囲まれたメッセージ キーとなり、⧼message-key-foo⧽ のように表示されます。 古いバージョンの MediaWiki では、メッセージキーは ASCII の山括弧で返され (<message-key-foo> のように)、無効な HTML 要素や偽の HTML 要素が生成される可能性がありました。 In the case where the message key does not exists, the .exists() method of the returned message object will also return false instead of true.

To use a message that must not go through the parser (e.g. when passing JSON data as messages, or when the message will be used as preloaded text of a page), use:

mw.message( 'foobar' ).plain()

形式のオプション

If you don't specify the output format, mw.message just returns a Message object. To output the message itself, you should specify an output format. The formats are mostly the same as in PHP side:

  • mw.message( 'foobar' ).plain() Returns the message text as-is; only parameters are substituted.
  • mw.message( 'foobar' ).text() Transforms the message text (all supported {{}} blocks are replaced with transformed results). See #Feature support in JavaScript for details of what is supported. For example, certain keywords ({{int:}}, {{GENDER}}, {{SITENAME}} etc.) work without parameters, but tranclusion (e.g. {{MediaWiki:}}) and server-side Magic words such as {{NUMBEROFEDITS}} or {{ns:Project}} do not work,
  • mw.message( 'foobar' ).escaped() HTML escaped version of text.
  • mw.message( 'foobar' ).parse() Parses the message text from wikitext to HTML. This supports everything from text mode, as well as most links, and allow listed HTML.
  • mw.message( 'foobar' ).parseDom() Like parse(), but returns a jQuery collection instead of a HTML string.
警告 警告: If the mediawiki.jqueryMsg module is not loaded, all of the above methods behave essentially like plain() with possible escaping.
There is no equivalent of parseAsBlock. Where necessary, wrap the output in a block element yourself.

パラメーター

Parameters can be specified as additional arguments to mw.message(). They can be passed as strings or as DOM nodes / jQuery collections.

Unlike in PHP, wikitext in the parameters is not parsed. Effectively, all string parameters behave like plaintextParams().

DOM/jQuery parameters can be used to achieve the equivalent of rawParams().

There is no support for other parameter formats. Don't use the formatnum magic word in messages. Always format the numbers in code. In JavaScript, instead of numParams(), you must format numbers before passing them as parameters, using mw.language.convertNumber().

$( '<div>' ).text( mw.message( 'translate-msggroupselector-view-subprojects', mw.language.convertNumber( count ) ).text() );

Feature support in JavaScript

警告 警告: JS メッセージでのウィキテキスト サポートには mediawiki.jqueryMsg モジュールの読み込みが必要です。読み込まれていない場合、これらの機能は黙って無視されます。

JavaScript messages only support a small subset of wikitext syntax. Supported features include:

  • Internal links (except pipe trick)
  • Explicit external links (no auto-numbered and free links)
  • The magic words SITENAME, PAGENAME, PAGENAMEE; since MW 1.38: SERVERNAME; since MW 1.43: CONTENTLANGUAGE
  • The parser functions PLURAL, GENDER, GRAMMAR, int, ns, formatnum, lc, uc, lcfirst, ucfirst; since MW 1.44: fullurl
  • HTML tags which are allowed in wikitext (HTML must be well-formed)
  • HTML entities &#039;, &quot;, &lt;, &gt;, &amp;
  • The ‎<nowiki> tag

Notable wikitext syntax that is not supported:

  • テンプレート
  • Non-local interwiki links
  • All other parser functions and magic words
  • Modules (for example Module:String)
  • All other XML-like tags (extension tags)
  • Bold and italic ''', '' (use ‎<b>, ‎<i> instead)
  • Lists using *, # (use ‎<ul> or ‎<ol>, ‎<li> instead)
  • Definition lists / indents using ;, : (use ‎<dl>, ‎<dt>, ‎<dd> instead)
  • Multiple paragraphs (use ‎<p> instead)
  • コメント <!-- -->
  • Some types of nesting (e.g. {{PLURAL:$1|<strong>$1</strong>}})

The doc-jqueryMsg template can be used to document such messages, to let translators know which wikitext restrictions apply.

mw.msg

The mw.msg() function is commonly used as a shortcut for mw.message().text().

Exporting messages through ResourceLoader callbacks

If you need to process a message on the server and send the result to the client (e.g. because you need to parse the message using parsing features that aren't supported in JS), you can do that with a package files callback in your ResourceLoader module. When you do this, take care to use $context->msg(), because using wfMessage() will cause errors.

Using messages in Lua

Modules written in Lua using Scribunto run similarly to templates and have access to MediaWiki messages. The MediaWiki Lua library includes the mw.message class for processing messages. Refer to the full Lua message library documentation for the full API. Here is a simple example:

local p = {}

function p.nmembers( frame )
	local nmembersMsg = mw.message.new( 'nmembers' )
	nmembersMsg:numParams( 3 ) -- This ensures number localization
	-- Show the message in the language of the wiki. frame:preprocess expands the {{plural}} clause.
	return frame:preprocess( nmembersMsg:plain() )
end

return p

Using messages in Vue.js

Notes about gender, grammar, plural

See also #Switches in messages…; the syntax itself is documented at Help:Magic words#Localization and related.

In general, GENDER, GRAMMAR and PLURAL magic words work identically in both PHP and JavaScript sides.

  1. You must use text, escaped, parse or parseAsBlock output formats for them to work.
  2. You need to pass the relevant parameter as normal parameter to the message.
    • The parameter is the number for PLURAL; the plain text or wikitext-escaped username for GENDER in PHP; the gender from preferences or a user object for GENDER in JavaScript (see below).
    • For enabling plural and correct number localization in PHP, you need to use numParams for the number, see also #Chaining.
    • For enabling plural and correct number localization in JavaScript, you need to use mw.language.convertNumber for the number

PLURAL syntax example

# Simple plural
'key' => '$1 crying {{PLURAL:$1|baby|babies}}'

GENDER in JavaScript

This needs explicit jqueryMsg, see #Using messages in JavaScript.

If you have a message, say, "message-key-gender-foo": "{{GENDER:$1|he|she|they}} created an article", in JavaScript, you can use it as given below:

mw.message( 'message-key-gender-foo', 'male' ).text(); // returns 'he created an article'
mw.message( 'message-key-gender-foo', 'female' ).text(); // returns 'she created an article'
mw.message( 'message-key-gender-foo', 'unknown' ).text(); // returns 'they created an article'

Instead of passing the gender directly, we can pass any "User-like" object with a gender option. For example, the current user object mw.user.

var user = mw.user; // current user
mw.message( 'message-key-gender-foo', user ).text(); // The message returned will be based on the gender of the current user.

If the gender passed is invalid or unknown, the gender neutral form will be used as defined for each language. Pass 'unknown' if you intentionally want the neutral form.

Finally, if you want to use the gender of the current user, you can pass an empty string:

// the following line illustrates the message content, you can run this snippet on developer console
mw.messages.set( 'message-key-gender-foo', '{{GENDER:$1|male|female|unknown}}' );
mw.user.options.values.gender = 'female'; // temporarily manipulate your gender preference
mw.message( 'message-key-gender-foo', '' ).text(); // return value depends on your gender preference

PLURAL in JavaScript

This needs explicit jqueryMsg, see #Using messages in JavaScript.

メッセージ 'message-key-plural-foo' => 'There {{PLURAL:$1|is $1 item|are $1 items}}' などが JavaScript 形式の場合、以下のように使ってください。

mw.message( 'message-key-plural-foo', count ).text();
// 戻り値は count = 1 のとき 'There is 1 item'
// 戻り値は count = 6 のとき 'There are 6 items'

関連項目

注記

  1. While using this mode to display HTML content is possible, it is recommended to use wikitext and use the parse() mode to transform it into HTML.
  2. More in general, use $this->msg() in non-static functions of IContextSource objects.