In Magento 1 I use this code:

<?php echo $this->__('some <a href="%s">text here</a>', Mage::getUrl('some/url/here')); ?>

How can I use in Magento 2?


Your solution might look something like this:

<a href="<?php echo $block->escapeUrl($this->getBaseUrl().'customer/address/');?>">
   <?php echo $block->escapeHtml(__('Street Address %1', $_i)); ?>

All URLs and translated content should be escaped to prevent XSS. Also, HTML tags shouldn't be translated.

Also, you can wrap this code by an own method.

| improve this answer | |
  • can we use %s instead of %1? – jafar pinjar Oct 23 '18 at 6:48

HTML code should not be used directly in a translation string, instead use a placeholder (i.e. %1) to represent it, and put it's value in a subsequent parameter to the translation method.

<?= __('some %1text here%2', '<a href="' . $block->getUrl('some/url/here') .'">', '</a>') ?>

The Magento core team uses this approach throughout their code base.

For example in...


| improve this answer | |

Use like this

<?= __('Street Address %1', $_i) ?>


<?= __('Customer address <a href="%s">link</a>!', $this->getBaseUrl().'customer/address/') ?>

The string in the CSV file should have double quotes:

"Customer address <a href=""%s"">link</a>!"
| improve this answer | |
  • Any html tags should not be in the translation function. – joni jones Jun 10 '16 at 9:12
  • @jonijones Incorrect. Sometimes you need to translate strings where a link could appear in the middle. – Design by Adrian Nov 2 '16 at 18:58
  • 2
    This isn't correct, you use sprintf() after Magento translated the string: echo sprintf( __('My string with <a href="%s">link</a>') , $myLink ) and the string in the CSV file should have double quotes: "My string with <a href=""%s"">link</a>" – Design by Adrian Nov 2 '16 at 19:29
  • @DesignbyAdrian, a string should be translated without reference to any HTML tags. You don't translate tags, you translate text output. Also, translation can break tags. – joni jones Nov 3 '16 at 7:59
  • @jonijones But a link can appear in different places in a sentence depending on language. I know it's wrong, but if the client wants only part of a sentence to be highligted, what's are the options? – Design by Adrian Nov 3 '16 at 10:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.