Creating Dynamic Title for Custom page in Drupal 8

In some cases you may need to generate dynamic titles for pages like node view page, you can do it by routing.yml file itself by adding one param

modulename.page:
 path: '/custompage'
 defaults:
  _controller: '\Drupal\modulename\Controller\DemoController::getPage'
  _title_callback: '\Drupal\modulename\Controller\DemoController::getPageTitle'
 requirements:
  _permission: 'access content'

Create src folder in your module path, create controller folder and create DemoController and add getPageTitle method in demo controller class