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?
Magento Stack Exchange is a question and answer site for users of the Magento e-Commerce platform. It only takes a minute to sign up.
Sign up to join this communityIn 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)); ?>
</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.
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
Magento2 give possibilities to translate links and use it. It could be safely done in this way:
__('Only registered users can write reviews. Please <a href="%1">Sign in</a> or <a href="%2">create an account</a>', $block->getLoginLink(), $block->getRegisterUrl())
where %1 is $block->getLoginLink() and %2 is $block->getRegisterUrl()
BUT for correct showing on the frontend, need to use escapeHtml this translation with allowed tags for escaping $block->escapeHtml(...)
So, to show url like typical <a href="">
tag, we need to do the following:
$block->escapeHtml(__('Only registered users can write reviews. Please <a href="%1">Sign in</a> or <a href="%2">create an account</a>', $block->getLoginLink(), $block->getRegisterUrl()), ['a'])
where add ['a'] tag like allowed tag for escaping.
In translation file (i18n/en_US.csv), it should looks like:
"Only registered users can write reviews. Please <a href=""%1"">Sign in</a> or <a href=""%2"">create an account</a>","Only registered users can write reviews. Please <a href=""%1"">Sign in</a> or <a href=""%2"">create an account</a>"
P.S. I took this example from core file: vendor/magento/module-review/view/frontend/templates/form.phtml , so I think, this approach is also valid
Use like this
<?= $block->escapeHtml(__('Street Address %1', $_i)) ?>
or
<?= $block->escapeHtml(__('Customer address <a href="%s">link</a>!', $block->escapeUrl($this->getBaseUrl().'customer/address/'))) ?>
The string in the CSV file should have double quotes:
"Customer address <a href=""%s"">link</a>!"
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>"
Nov 2, 2016 at 19:29