Magento 2 : How to concat a string variable to option value in knockout template which already bind to i18n string?

magento.stackexchange https://magento.stackexchange.com/questions/265596

Question

I've knockout template which contains the following line:

<option value='industrial' data-bind="i18n: 'Industrial'"></option>

anyone knows how to add variable to 'Industrial' eg.

<option value='industrial' data-bind="i18n: 'Industrial' + window.checkoutConfig.hrFlag"></option>

the above line didn't work.

Was it helpful?

Solution

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

  1. Link the mage/translate library

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

  2. 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.

Reference : https://devdocs.magento.com/guides/v2.3/frontend-dev-guide/translations/translate_theory.html

For phtmls $t does the same thing as mage/translate so you can do following ;

<option value='industrial' data-bind="i18n: $t('Industrial %1').replace('%1', window.checkoutConfig.hrFlag)"></option> 
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top