Translate anything

This simple example will create a small form that calls an external translation service to translate the content entered on that form. The result will be displayed underneath the source text that was entered.

The form will be called "translate_anything" and can then be called in a regular SPIP template file using the tag #FORMULAIRE_TRANSLATE_ANYTHING or within an article by using <formulaire|translate_anything>.

As with most CVT forms, it operates using two files:

formulaires/translate_anything.html for the HTML section

formulaires/translate_anything.php for the PHP analysis and processing functions.

The HTML template

The template for the form will receive two data entry fields of the textarea type: the first for writing the content to be translated, and the second to display the results of the translation once the calculation has been performed. This second field is only displayed when it actually has some content.

The two fields named "traduire" and "traduction" (source and destination for the translation). The same template could be written using the "Saisies" plugin with the content between <ul> and </ul> represented as follows:

It is with the "process" function that things now get a little complicated. The content needs to be sent to a remote service (we use Google Translate in this example), the return data retrieved and processed, and then displayed on our form.

To do all this, the script starts by calculating the URL for the remote service based on that service’s published API. We use SPIP’s parametre_url PHP function to cleanly add the variables to the service’s URL. Thanks to another function, recuperer_page which is used to retrieve the code returned by a call to an URL, the service’s returned data is stored in the $trad variable.

The service returns the data formatted in JSON format, so it must be extricated using the json_decode function. depending on the information returned, the translation will be determined as having been successful or not. The message is adapted depending on this outcome.

The set_request() functions forces the saving of a variable value that can then later be retrieved using _request(). This allows the next loading of the form to retrieve the value of the "traduction" field to send it into the template’s context.

Note: It is possible that a cleaner method could be developed for future versions of SPIP in order to transit the data between the processing and loading phases using a new parameter in the processing return table.