📜 ⬆️ ⬇️

JQuery plugin for translating pages using html5 data- * attributes

Good day!

I want to share my experience to translate the pages of the site with the help of the simplest jQuery plugin and such a nice new html5 bun, as data- * attributes.

So, the goal: the ability to easily and quickly provide support for multiple languages ​​for the developed web application.
')
Now for some code. Suppose we have such a simple html markup:

<h1 data-translate-key="HEADING-ONE">Heading 1</h1> <p data-translate-key="SOME-TEXT">Some text in tag P</p> <p data-translate-key="ANOTHER-TEXT">another text</p> 


As you can see in the listing above, we have several html elements that have a key declared using the data-translate-key attribute for translation, using which we will receive the text itself from the dictionary. Also inside the tags is the text "by default".

The organization of the dictionary will be implemented by means of standard JavaScript objects:

 var dict = { en: { 'SITE-TITLE': 'Site title', 'HEADING-ONE': 'Heading 1', 'SOME-TEXT': 'Some text in tag P', 'ANOTHER-TEXT': 'another text1' }, ru: { 'SITE-TITLE': ' ', 'HEADING-ONE': ' ', 'SOME-TEXT': '     P', 'ANOTHER-TEXT': ' ' } }; 


As you can see in this example, we have two dictionaries. For Russian and English languages.

Now the most important thing. Actually the plugin itself. It has only a few lines of code:

 $.html5Translate = function(dict, lang){ $('[data-translate-key]').each(function(){ $(this).html( dict[ lang ][ $(this).data('translateKey') ] ); }); }; 


Here, as can be seen from the listing, we get all the elements of the html page that have the data-translation-key attribute and scroll through the entire array of these elements using the each callback. Later in each iteration, we set the text for each element, according to which dictionary is selected, and also according to the value of the data-translation-key attribute, for each specific element. The function accepts only two variables as arguments: dict - contains a dictionary object and lang - contains the names of the language that should be used now.

To apply the plugin it’s enough to do the following:

1. Connect the jQuery library.
2. Connect the plugin itself.
3. Mark up the html document by placing the data-translation-key attributes for the desired elements.
4. Create a dictionary (it is also recommended to connect it with a separate js file).
5. Call the translation function when the DOM document is ready and specify the necessary parameters to the function:

 $(document).ready(function(){ $.html5Translate(dict, 'en'); }); 


Here, as you can see, we call the translation function, indicating to it that we need to use the dict dictionary object and translate the text of all elements into English.

Thanks for attention.

Source: https://habr.com/ru/post/177083/


All Articles