4

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'));
  • Avoid $this->_view. You can use xml or from controller it's your choice – Sohel Rana Jan 11 '17 at 11:22
  • Ok, do you have any correct way to present it here? – Bartosz Kubicki Jan 11 '17 at 11:23
10

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

  • I've just encountred something similar for layout: <referenceBlock name="root"> <action method="setHeaderTitle"> <argument translate="true" name="title" xsi:type="string">Title</argument> </action> </referenceBlock> Is it deprecated and I should way you showed? – Bartosz Kubicki Jan 11 '17 at 11:41
  • 1
    You can use any of them. – Sohel Rana Jan 11 '17 at 11:44
  • It is better to use your way - it is simpler. – Bartosz Kubicki Jan 11 '17 at 11:46
  • in magento 2 I want to change "Related Products" to something else how can I? – ravisoni May 4 '18 at 14:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.