How can I use a link in string to translate at Magento 2?
-
29-09-2020 - |
Question
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?
Solution
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)); ?>
</a>
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.
OTHER TIPS
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...
vendor/magento/module-catalog/view/frontend/templates/product/list/toolbar/amount.phtml
Use like this
<?= __('Street Address %1', $_i) ?>
or
<?= __('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>!"
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange