Question

[EDIT]
This is outdated. The translation is not done anymore as described below
[/EDIT]
In Magento 1 the translatable texts needed in javascript were added in the jstranslate.xml file in the etc folder of a module and they were automatically added to the translator js object.
How can I add translatable texts to be used in javascript in Magento 2?
I found how to use text translations in Magento 2 but I don't know how to add new ones.

Here is an example on how to use them:

alert($.mage.__('Text to translate here'));
Was it helpful?

Solution

OK. I found a solution but it seams ugly to me.
In the layout handle of the page I need I add this:

<referenceContainer name="after.body.start">
    <block class="Magento\Framework\View\Element\Template" name="some-name-here" template="[Namespace]_[Module]::translate.phtml"/>
</referenceContainer>

then create the template translate.phtml in [Namespace]/[Module]/view/[frontend|adminhtml]/templates with this content:

<?php
$_data = array(
    'Text one to translate' => __('Text one to translate'),
    'Text two to translate' => __('Text two to translate'),
);
?>
<script type="text/javascript">
    require(["jquery","mage/translate"], function($){
        $.mage.translate.add(<?php echo Zend_Json::encode($_data) ?>)
    });
</script>

I really hope there is an other way of doing this.

OTHER TIPS

The default src for the translations in frontend seems to be /app/code/Magento/Translation/view/base/templates/translate.phtml

pointing to this block /app/code/Magento/Translation/Block/Js.php

which has this as dataprovider /app/code/Magento/Translation/Model/Js/DataProvider.php

So you could change the dependency to an own dataprovider, or intercept this one to add own translations, or add an own block of this type with own dataprovider.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top