Translate Theme Strings In Magento 2

Today, I will show you how to add theme strings so that the i18n tool can collect and add the strings to the dictionary.

 

1. String added in .phtml templates

<?php echo __('your string') ?>

- if in your string contain variable it will be:

<?php echo __('your string %1', $variable) ?>

 

2. Strings added in UI component templates

- When a string is added in the scope of an HTML element, both of the following examples result in the same output: 

<span data-bind="i18n: 'Your string'"></span>
<span translate="'Your string'"></span>

 

- When a string is added with no binding to an HTML element, both of the following examples result in the same output:

<!-- ko i18n: 'Your string' --><!-- /ko -->
<translate args="'Your string'"/>

 

- When a string is added as an attribute of an HTML element:

<input type="text" data-bind="attr: {placeholder: $t('First Name')}" />

 

3. Strings added in UI components configuration files

- In this example, the Delete string is added to the dictionary when the i18n tool is run:

<item name="label" xsi:type="string" translate="true">Delete</item>

 

- Translated strings that originate from .xml files will not render unless they are called with a __(<variable>) method in .php files. In this example, you would use a call similar to the following to display the translated Delete string.

__($this->config->getData('label'))

 

4. Strings added in Underscore templates

- To ensure that the text you add in .html Underscore templates is collected by the i18n tool, use the _.i18n('') Underscore function.

- When a string is added to the template:

<%= _.i18n('Hello') %>


- If the string contains a variable, use the variable placeholder:

<%= _.i18n('Hello %1').replace('%1', yourVariable) %>


In this example, the ‘Hello %1’ string is added to the dictionary when the i18n tool is run.

 

5. Strings added in .js files

- To ensure that the text you add in a .js file is collected by the i18n tool and added to the dictionary:

 

- Link the mage/translate library:

define (['jquery', 'mage/translate'], function ($) {...});

 

- Use the $.mage.__('') function when adding a string:

$.mage.__('<string>');

 

- If your string contains a variable, to add a placeholder for this variable to the string stored in the dictionary, use the syntax similar to the following:

$.mage.__('Hello %1').replace('%1', yourVariable);

In this example, the 'Hello %1' string is added to the dictionary when the i18n tool is run.

 

Done, see you in the next post.