Open footer block link in new tab/window
Question
I've customized one of the footer link blocks within Magento 2's Luma theme in the default.xml file (htdocs/app/design/frontend/Ouho/outwardhound/Magento_Theme/layout/default.xml) with an external link:
<block class="Magento\Framework\View\Element\Html\Link\Current" name="external-link">
<arguments>
<argument name="label" xsi:type="string">External Link Name</argument>
<argument name="path" xsi:type="string">http://example.com</argument>
</arguments>
</block>
My question is, how can I get this link to open within a new tab using the xml/block/argument structure? I've seen mention of using <aParams>target="_blank"</aParams>
elsewhere but it doesn't seem to function no matter where i place it within the code here.
Solution
The following will allow you to open a link in a new window (tested in Magento 2.2.3). Note specifically the attributes
argument:
<referenceBlock name="footer_links">
<block class="Magento\Framework\View\Element\Html\Link\Current" name="about-link" after="contact-us-link">
<arguments>
<argument name="label" xsi:type="string" translate="true">About Us</argument>
<argument name="path" xsi:type="string">about</argument>
<argument name="attributes" xsi:type="array">
<item name="target" xsi:type="string">_blank</item>
</argument>
</arguments>
</block>
</referenceBlock>
If, for example, we look at the _toHTML
and getAttributesHTML()
methods of the Magento\Framework\View\Element\Html\Link\Current
class, we see how the attributes are appended to the link. Specifically:
private function getAttributesHtml()
{
$attributesHtml = '';
$attributes = $this->getAttributes();
if ($attributes) {
foreach ($attributes as $attribute => $value) {
$attributesHtml .= ' ' . $attribute . '="' . $this->escapeHtml($value) . '"';
}
}
return $attributesHtml;
}
So, the item name
attribute and value turns into the <a>
tag’s attribute and value, respectively.