Google translation requires creating a project with Google Developers Console. Moreover, billing needs to be enabled before the API can be used in your application. You can create a new project or use out of the box project created in the Developer console.
A drop down list on the page will show all the available languages for the translation. Selecting a language in the drop down list will send the page content and title to translation API and get back the translated text. Finally, the page will be updated with translated text.
A SharePoint page layout should be created in order to make this reusable across all pages created from that layout instead of using the code in each page. In this post we will focus on the actual code for translation.
_spPageContextInfo will allow us to access the current page item ID and the current list ID. The page content is stored in PublishingPageContent field. The title and content can be read by calling the above function:
The languages method of the google api gives the list of available languages. Following code shows how a call to this method can be used to build the drop down list:
The GET request can be made to the api to translate the text. However, The URL for the GET, including parameters, must be less than 2K characters.
Example of a GET request from the documentation:
Here "q" specifies the text which is to be translated. Multiple source texts can be sent for translation by specifying this parameter for each text. Example:
If the text is going to be longer than 2K, then a POST request can be made as described in the documentation:
Note: You can also use POST to invoke the API if you want to send more data in a single request. The q parameter in the POST body must be less than 5K characters. To use POST, you must use the X-HTTP-Method-Override header to tell the Translate API to treat the request as a GET (use X-HTTP-Method-Override: GET).
Now, in our case we will use POST and send text of the title and page content together in one call to the translation service.
Observe, the use of traditional attribute in ajax call. This will allows us to specify both page content and page title in "q" parameter. If the request is successful, we update page content and title using JQuery. Here is the complete code:
Sample page having Title and Content in English: