How to Translate a String by Code in Magento 2

Translate a string by code

In this topic we will see about How to Translate a String by Code in Magento 2 through 5 steps:

  1. In .ptml files
  2. In email template
  3. Strings added in UI components’ templates
  4. Strings added in UI components configuration files
  5. Strings added in .js files

In Magento 2, you can setup multi-languages. But to translate the string in Magento 2, in the source code, you must use the function to translate

1. In .ptml files

  • Use the function  __()
__(‘<your_string>’)
  • For example:
<h3><?php echo __('How to translate') ?></h3>
  • If your string contains a variable, you can use::
<span style="font-weight: 400;">  </span>
<h3><?php echo sprintf(__('How to translate %s'), $yourVariable) ?></h3>
  • In this example, the ‘Hello %s’string is added to the dictionary when the i18n tool is run.

2. In email template

If your theme contains a custom email template, use the {{trans}} directive.

3. Strings added in UI components’ templates

  • A string is added in the scope of an HTML element:
  <span data-bind="i18n: 'How to translate'"></span>
  • A string is added with no binding to an HTML element:
  <!-- ko i18n: 'How to translate' --><!-- /ko -->

4. Strings added in UI components configuration files

  • Use the translate attribute in .xml files:
  <item name="label" xsi:type="string" translate="true">How to translate</item>

5.Strings added in .js files

  • Define
(['jquery', 'mage/translate'], function ($) {...});
  • Use the $.mage.__(”) function when adding a string:
$.mage.__('<string>');
  • If your string contains a variable:
$.mage.__('How to translate %1').replace('%1', yourVariable);

Conclusion

The 5 steps I mentioned above is the shortest process for you to Translate a String by Code in Magento 2. With this guide, you can manage the String by Code in Magento 2 easily. Every store has a String by Code in Magento 2 with many attributes.

For more Magento Kb, visit Webnexs Magento Knowledge Base.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *