GeezerVisonThe World Wide Web, restored to 800 pixels of glory. | ||||||||||||||
| Home|About|Gaming cabinet|Archives|How it works|Starter sites | ||||||||||||||
GeezerVison is showing www.mediawiki.org — Manual:Messages API - MediaWiki MediaWiki messages can be used in the code through the Message class and its associated methods.
Message parametersSome messages take parameters.
They are represented by The list of parameters defined for each specific message is placed in special file "qqq.json" located in "languages/" folder of MediaWiki - read more in Message documentation. It's preferable to use whole words with the PLURAL, GENDER, and GRAMMAR magic words.
For example, Referring to other messagesIt's sometimes convenient to refer to sub-messages in a message, e.g. in phrases like "Use the X button" or "Visit the Y page", to ensure that the translations are consistent. To do so, you may use the following syntax:
If you need anything more complicated (e.g. the sub-message used depends on configuration), parse it in your code and pass the whole sub-message as a parameter. Example: 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}}]]. Switches in messages…Parameters values at times influence the exact wording, or grammatical variations in messages.
We don't resort to ugly constructs like "$1 (sub)page(s) of his/her userpage", because these are poor for users and we can do better.
Instead, we make switches that are parsed according to values that will be known at run time.
The static message text then supplies each of the possible choices in a list, preceded by the name of the switch, and a reference to the value that makes a difference.
This resembles the way Parser functions are called in MediaWiki.
Several types of switches are available.
These only work if you do full parsing, or …on numbers via PLURALMediaWiki supports plurals, which makes for a nicer-looking product. For example: 'undelete_short' => 'Undelete {{PLURAL:$1|one edit|$1 edits}}', If there is an explicit plural form to be given for a specific number, it is possible with the following syntax: 'Box has {{PLURAL:$1|one egg|$1 eggs|12=a dozen eggs}}.'
Be aware of PLURAL use on all numbersSee also: translatewiki:Plural and Help:Magic words#plural
When a number has to be inserted into a message text, be aware that some languages will have to use PLURAL on it even if always larger than 1. The reason is that PLURAL in languages other than English can make very different and complex distinctions, comparable to English 1st, 2nd, 3rd, 4th, … 11th, 12th, 13th, … 21st, 22nd, 23rd, … etc. Do not try to supply three different messages for cases like "no items counted", "one item counted", "more items counted". Rather, let one message take them all, and leave it to translators and PLURAL to properly treat any possible differences of presentation for them in their respective languages. Always include the number as a parameter if possible.
Always add Fractional numbers are supported, but the plural rules may not be complete. Pass the number of list items as parameters to messages talking about listsDon't assume that there's only singular and plural.
Many languages have more than two forms, which depend on the actual number used and they have to use grammar varying with the number of list items when expressing what is listed in a list visible to readers.
Thus, whenever your code computes a list, include …on user names via GENDER'foobar-edit-review' => 'Please review {{GENDER:$1|his|her|their}} edits.' If you refer to a user in a message, pass the user name as parameter to the message and add a mention in the message documentation that gender is supported. If it is likely that GENDER will be used in translations for languages with gender inflections, add it explicitly in the English language source message. If you directly address the currently logged-in user, leave the user name as parameter empty: 'foobar-logged-in-user' => 'You said {{GENDER:|you were male|you were female|nothing about your gender}}.'
If you include the user name into the message (e.g. Users have grammatical gendersSee also: translatewiki:Gender and Help:Magic words#gender
When a message talks about a user, or relates to a user, or addresses a user directly, the user name should be passed to the message as a parameter. Thus languages having to, or wanting to, use proper gender dependent grammar, can do so. This should be done even when the user name is not intended to appear in the message, such as in "inform the user on his/her talk page", which is better made "inform the user on {{GENDER:$1|his|her|their}} talk page" in English as well. This does not mean that you are encouraged to "sexualise" messages' language: please use gender-neutral language whenever this can be done with clarity and precision. …on use context inside sentences via GRAMMARGrammatical 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 messagesThe other (much simpler) issue with parameter substitution is HTML escaping. Despite being much simpler, MediaWiki does a pretty poor job of it. Using messages in PHP
Here is a simple example: $out = Xml::submitButton( wfMessage( 'submit' )->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 The following sections explain the code. ParametersGiven 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+
Each function from the second group formats the value in a specific way before the substitution.
LanguageTo 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 escapingThe Message class, and thus the object returned by wfMessage(), has five output modes:
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 Which output mode to useGenerally speaking, the most common modes you will use are Some common cases:
Method chainingMost 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 messagesThe general message function in MediaWiki is 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
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
Getting the messages to the clientTo 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 moduleSee also: Manual:$wgResourceModules
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 Example (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
You can use the following code:
// 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 // 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 messagesThe messages defined in the above example will be available at client side and can be accessed by For example: $( '<div>' ).text( mw.message( 'translate-msggroupselector-projects' ).text() ); Note how we use jQuery If your message contains wikitext formatting, you can instead use the following: $( '<div>' ).append( mw.message( 'translate-msggroupselector-projects' ).parseDom() ); Here we use jQuery In older code you might also encounter the following: ( $( '<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.
If the message key is not found in any i18n file, the result will be the message key in curved angle brackets U+29FC/U+29FD (part of mathematical symbols), like 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() Format optionsIf 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:
There is no equivalent of parseAsBlock. Where necessary, wrap the output in a block element yourself.
ParametersParameters can be specified as additional arguments to Unlike in PHP, wikitext in the parameters is not parsed.
Effectively, all string parameters behave like DOM/jQuery parameters can be used to achieve the equivalent of There is no support for other parameter formats.
Don't use the $( '<div>' ).text( mw.message( 'translate-msggroupselector-view-subprojects', mw.language.convertNumber( count ) ).text() ); Feature support in JavaScript
JavaScript messages only support a small subset of wikitext syntax. Supported features include:
Notable wikitext syntax that is not supported:
The doc-jqueryMsg template can be used to document such messages, to let translators know which wikitext restrictions apply. mw.msgThe Exporting messages through ResourceLoader callbacksIf 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 Using messages in LuaModules 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.jsSee also: Vue.js#Internationalization
Notes about gender, grammar, plural
In general, GENDER, GRAMMAR and PLURAL magic words work identically in both PHP and JavaScript sides.
PLURAL syntax example# Simple plural 'key' => '$1 crying {{PLURAL:$1|baby|babies}}'
GENDER in JavaScriptThis needs explicit
jqueryMsg, see #Using messages in JavaScript.If you have a message, say, 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 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 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 JavaScriptThis needs explicit
jqueryMsg, see #Using messages in JavaScript.If you have a message, say mw.message( 'message-key-plural-foo', count ).text(); // returns 'There is 1 item' if count = 1 // returns 'There are 6 items' if count = 6 See alsoNotes | ||||||||||||||
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |