Hello, Magento Folks,
Last time we learned how you can Create Custom log files using a module in Magento 2. Today, we are going to learn how to write translatable strings in Email, PHTML, UiComponents, js, etc.
In any version of Magento 2, you can setup multi-languages, but to translate strings in Magento 2, you need to know some functions that are useful in the source code. There are different types of approaches to write a translatable string in Magento 2 frontend. Like Email, PHTML, UiComponents, Js, etc.
So, let’s check out how to write translatable strings with the help of codes.
Note: You can check all translatable string at
pub\static\frontend\Themes\Yourtheme\<language>\js-translation.json
Let’s first look at how to translate strings in PHTML:
<?= __('Magecomp Extension Developer);?> <?= __("Magecomp has %s extension in Magento 2", $count); ?>
Let’s first look at how to translate strings in Email templates:
{{trans "'Magecomp Extension Developer "}} {{trans " you have %items items in Order." items=shipment.getItemCount}}
Let’s first look at how to translate strings in UI Component templates:
<span data-bind="i18n: 'Magecomp Extension Developer’ "></span> <input type="text" data-bind="attr: {placeholder: $t("'Magecomp Extension Developer ")}"/> <translate args="''Magecomp Extension Developer '"></translate> <span translate="''Magecomp Extension Developer '"></span>
Let’s first look at how to translate strings in JS files:
require the jquery and mage/translate modules, then $.mage.__( 'Magecomp Extension Developer’) $.mage.__("%1 items in your bag").replace("%1", numberOfItems); mage/translate $t('Magecomp Extension Developer ')
Note: you must use the $t object of Mage/Translate. You can’t change the name of $t like,
Will work ?
Define([ mage/translate ],function($t) { $t(“Magecomp Exenstion Developer”); });
Will Not work ?
Define([ mage/translate ],function($tranlate) { $tranlate(“Magecomp Extension Developer”); });
So, this was it for the day. Now, you are able to write translatable strings in Email, PHTML, UiComponents, and Js, etc. The code strings above are just for the reference only you can customize it and implement it for your use as per your needs. If you face any problem while during so then contact our support team.
Lastly, feel free to comment below and let us know what you feel about this article. Also, you can share this with your Magento colleagues and partners.
Happy Coding?