I am using the REST API in Drupal 9 and am using JavaScript template literals to generate some of the data.
For example, to generate a list of products that are pulled from the API, I am using this code.
<span class="products">
${Drupal.t(object.field_supplier_products)}
</span>
This returns what I have under field_supplier_products, so for example "Product 1, Product 1, Product 3", but I cannot find the string translations.
This is a multilingual site and these product names need to be translated.
With the following code, I can see the translations.
<span class="products">${Drupal.t('Product One')}</span>
<span class="products">${Drupal.t('Product Two')}</span>
<span class="products">${Drupal.t('Product Three')}</span>
Is there any possible way or workaround to use Drupal.t()
with variables?
I am using the Drupal RESTful Web Services Module to have a REST API for a view. I created a view that has all my products.
I have a JavaScript file product.js that is used to generate markup on my products.html.twig file.
(function ($, Drupal) {
if ( document.querySelector('#products-page') ) {
$.ajax({
method: 'GET',
url: '/api/products/'
}).done(function (data, status, xhr) {
$.each(data, function (index, object) {
$('#products .wrapper').append(`
<div class="col-12 product">
<span class="products">${Drupal.t(object.field_supplier_products)}</span>
</div>
`)
});
});
}
})
With the following data, object.field_supplier_products
returns "product1"
.
{
"title": "Supplier 1",
"nid": "1",
"market_id": "2",
"product_id": "15",
"field_supplier_products": product1,
}
Drupal.t()
in the JS file making the call to the API? It's a little difficult to sort out your architecture to give a proper reply, so if you could explain the architecture, and where the call toDrupal.t()
is located, it would be easier to provide assistance.