12

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

1 Answer 1

25

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

13
  • 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? Commented Jan 11, 2017 at 11:41
  • 1
    You can use any of them.
    – Sohel Rana
    Commented Jan 11, 2017 at 11:44
  • It is better to use your way - it is simpler. Commented Jan 11, 2017 at 11:46
  • in magento 2 I want to change "Related Products" to something else how can I?
    – Ravi Soni
    Commented May 4, 2018 at 14:12
  • Another option is to change the original phrase using csv translations Commented Jul 15, 2019 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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