Magento 2 – Change Page Title in Controller or Block

blockscontrollersmagento2page-title

I have found two ways for changing page title and I don't know which one I should use.

1. Override prepareLayout() in block

protected function _prepareLayout()
{
    $this->pageConfig->getTitle()->set(__('Title') . ' - ' . $this->pageConfig->getTitle()->getDefault());
    return parent::_prepareLayout();
}

2. Change title via \Magento\Framework\App\ViewInterface in controller

in execute() method:

        $this->_view->getPage()->getConfig()->getTitle()->set(__('My Downloadable Products'));

Best Answer

You can do it in different ways - it's enough to use only one:

1. From controller

/** @var \Magento\Framework\View\Result\Page $resultPage */
$resultPage = $this->resultPageFactory->create();
$resultPage->getConfig()->getTitle()->set('Something');

2. From layout module_controller_action.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <title>Something..</title>
    </head>
</page>

NOTE - In most cases xml would be loaded first, so take in account that title can be changed in controller

Related Topic