97072e270041bbdcd8a903aac2b00e69c5817854
[lhc/web/wiklou.git] / resources / jquery / jquery.localize.js
1 /**
2 * Simple Placeholder-based Localization
3 *
4 * Call on a selection of HTML which contains <html:msg key="message-key" /> elements or elements with
5 * title-msg="message-key" or alt-msg="message-key" attributes. <html:msg /> elements will be replaced
6 * with localized text, elements with title-msg and alt-msg attributes will receive localized title
7 * and alt attributes.
8 * *
9 * Example:
10 * <p class="somethingCool">
11 * <html:msg key="my-message" />
12 * <img src="something.jpg" title-msg="my-title-message" alt-msg="my-alt-message" />
13 * </p>
14 *
15 * Localizes to...
16 * <p class="somethingCool">
17 * My Message
18 * <img src="something.jpg" title="My Title Message" alt="My Alt Message" />
19 * </p>
20 */
21 ( function( $ ) {
22 /**
23 * Localizes a DOM selection by replacing <html:msg /> elements with localized text and adding
24 * localized title and alt attributes to elements with title-msg and alt-msg attributes
25 * respectively.
26 *
27 * @param Object: options Map of options
28 * * prefix: Message prefix to use when localizing elements and attributes
29 */
30
31 $.fn.localize = function( options ) {
32 options = $.extend( { 'prefix': '', 'keys': {}, 'params': {} }, options );
33 function msg( key ) {
34 var args = key in options.params ? options.params[key] : [];
35 // Format: mw.msg( key [, p1, p2, ...] )
36 args.unshift( options.prefix + ( key in options.keys ? options.keys[key] : key ) );
37 return mw.msg.apply( mw, args );
38 };
39 return $(this)
40 .find( 'html\\:msg' )
41 .each( function() {
42 var $el = $(this);
43 $el
44 .text( msg( $el.attr( 'key' ) ) )
45 .replaceWith( $el.html() );
46 } )
47 .end()
48 .find( '[title-msg]' )
49 .each( function() {
50 var $el = $(this);
51 $el
52 .attr( 'title', msg( $el.attr( 'title-msg' ) ) )
53 .removeAttr( 'title-msg' );
54 } )
55 .end()
56 .find( '[alt-msg]' )
57 .each( function() {
58 var $el = $(this);
59 $el
60 .attr( 'alt', msg( $el.attr( 'alt-msg' ) ) )
61 .removeAttr( 'alt-msg' );
62 } )
63 .end();
64 };
65
66 // Let IE know about the msg tag before it's used...
67 document.createElement( 'msg' );
68 } )( jQuery );