How do can you change the page <title>
used within the <head>
tag in Magento 2 with LayoutXML?
In Magento 1 you could use:
<reference name="head">
<action method="setTitle"><title>Example Title</title></action>
</reference>
But I can't find a way to do this with M2, so far I've tried…
<head>
<title>Example Title</title>
</head>
Best Answer
As I've searched, Magento 2 sets the page title in the
Block
classes, more exactly in the_prepareLayout()
method with the$this->pageConfig->getTitle()->set($pageTitle)
instruction.To use the
_prepareLayout()
method and the functionality of$this->pageConfig
attribute,Block
classes needs to extend the\Magento\Framework\View\Element\Template
class.If you'll take a look in the
__construct(...)
construct of the\Magento\Framework\View\Element\Template
class, you'll find$this->pageConfig = $context->getPageConfig();
, which is an instance of\Magento\Framework\View\Page\Config
class, responsible with a vast majority of SEO stuff methods:setDescription(), getDescription(), setRobots(), getRobots()
and so on. Also, in this class, you'll find thegetTitle()
method, returning an instance of\Magento\Framework\View\Page\Title
. This class containsset($title)
metohd responsible for setting the page title.