How to convert a string by code in Magento 2? – Magento 2.3

In this blog, we will explain to you How to Translate a string by Code in the Magento platform through 5 stages:

  1. In .phtml files
  2. In email template
  3. Strings can be added in UI components templates
  4. Add strings UI components configuration files
  5. Add Strings in .js files
Get consulted with best-in-class Magento development experts

With this guide, you can handle the string by code in Magento simply. Each store has a string by code in Magento 2 with multiple elements.

Hi everyone. In Magento 2, you can setup multi-languages. Be that as it may, to change over the string in Magento, in the source code, you should make utilization of the accompanying function to convert.

Convert a string by code in Magento 2

How to convert a string by code in Magento 2? - Magento 2.3

In .phtml files

  • Use the function _() _(‘<your _string>’)

For example:

<h3><?php echo __('How to translate') ?></h3>

If your string includes a variable, you can use the following:

<span style="font-weight: 400;">  </span>
<h3><?php echo sprintf(__('How to translate %s'), $yourVariable) ?></h3>

In this example, ‘Hello% s’ is added to the string dictionary when i18n is running

In email template

On the off chance that your topic incorporates custom email format, utilize {{trans}} directive

Strings can be included in UI segments formats

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

Include Magento 2 string UI segments configuration files

  • Utilize the convert elements in .xml documents: :
<item name="label" xsi:type="string" translate="true">How to translate</item>

Add Strings in .js files

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

The above-mentioned venture is the straightforward procedure for you to change over a string by code on the Magento website. With these steps, you can deal with the string by code in the Magento platform just. Each store has a string by code in Magento site with numerous components.

Last Update: February 9, 2021  

February 27, 2018   2691   Nandini Ramachandran    Code, Magento 2 Tutorial, Magento2    
Total 4 Votes:

Tell us how can we improve this post?

+ = Verify Human or Spambot ?

Leave a Reply

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