Th problem is due to the fact that you are attempting to translate a variable, rather than a literal string:
Drupal.t(object.field_supplier_products)
In Drupal, variables should not be translated, for both security reasons, and to keep the translations table clean. Now, on the server side in PHP if you were to use the t()
function around a variable, for example t($color)
it would throw a warning, but the value should still be translatable (I haven't tried/checked in a few years). But if I recall correctly, with JS and the Drupal.t()
function, it is not possible to translate variables at all. This is because the script Drupal actually parsed for the values by Drupal and re-generated with the translated values, cached with the translated values and this new file is sent to the browser. So no translation actually happens on the browser, the translation is actually enacted by PHP on the server, and a new file is generated before ever sending the file to the browser.
The solution is to ensure that your values are translated in the REST API so that they are already translated when your JS receives them, and will not require use of the Drupal.t()
function. From your post it appears that the REST endpoint is also a Drupal instance, so to do this on the REST server you would:
- Set up the REST API server to be a multilingual site, with language detection by URL.
- Make your request to the API using the multilingual URL for the language to be retrieved.
For example, if your multilingual site differs by path prefix, you will have:
http://www.example.com/path/to/restserver
[primary langauge]
http://www.example.com/[LANGUAGE_PREFIX]/path/to/restserver
(LANGUAGE_PREFIX language)
Then, your JS would request the REST API from the relevant language path.
I often find it's beneficial to generate the URL on the server side, and pass this PHP generated URL, which will contain the language prefix for the current language, to the JS which then calls URL dynamically.
This is first done by creating a library that adds your JS file, and has a dependency on Drupal settings:
example_library:
js:
path/to/file.js: {}
dependencies:
- core/drupalSettings
Then, your render element would attach the library, and pass the URL to the JS file in the library:
use Drupal\Core\Url;
$page[
'some_element' => [
'#prefix' => '<div id="example_placeholder">',
'#suffix' => '</div>',
'#markup' => $this->t('Placeholder'),
'#attached' => [
'library' => ['[MODULE]/example_library'],
'drupalSettings' => [
'exampleModule' => [
'ajaxCallbackUrl' => Url::fromRoute('[RESTAPI ROUTE]', [], ['absolute' => TRUE])->toString(),
],
],
],
],
];
Now, the script file.js
will have access to the REST API URL with the language prefix, in the drupalSettings.exampleModule.ajaxCallbackUrl
variable.
file.js:
function(drupalSettings) {
function doSomething() {
console.log(drupalSettings.exampleModule.ajaxCallbackUrl);
}
}(drupalSettings));