1. In .ptml files
- Use the function __()
__(‘<your_string>’)
- For example:
1
|
<h3><?php echo __(‘How to translate’) ?></h3>
|
- If your string contains a variable,you can use::
1
|
<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 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:
1
|
<span data–bind=“i18n: ‘How to translate'”></span>
|
- A string is added with no binding to an HTML element:
1
|
<!— ko i18n: ‘How to translate’ —><!— /ko —>
|
4.Strings added in UI components configuration files
- Use the translate attribute in .xml files:
1
|
<item name=“label” xsi:type=“string” translate=“true”>How to translate</item>
|
5.Strings added in .js files
- Define
1([‘jquery’, ‘mage/translate’], function ($) {...});
- Use the $.mage.__(”) function when adding a string:
1
|
$.mage.__(‘<string>’);
|
- If your string contains a variable:
1
|
$.mage.__(‘How to translate %1’).replace(‘%1’, yourVariable);
|
The 5 steps I mention 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.