1

I have a custom route and module that outputs content to a page.

I want to also have a page/content title/header on the page. I've figured out how to set the browser title, but I can't figure out how to add the headline title.

When creating a basic page with no custom template, the headline is part of that html. I want to replicate this.

Here is what I have in my controller:

return array(
    '#title' => 'This sets the browser title',
    '#markup' => 'This is the html output',
);

I've been banging my head on this for a few days now... help!

I've already tried setting $variables['title'] in theme_preprocess_page_title, but that doesn't seem to get called. I've also tried it in preprocess_page, but that does nothing.

To clarify - I am wanting to change the text that is by default displayed in <h1 class="page-header"> from within my controller.

3

You set the title in the route in the _title parameter:

mymodule.page:
  path: '/mymodule/page'
  defaults:
    _title: 'Page title'
    _controller: '\Drupal\mymodule\Controller\MyController::controller'

Or you can use a route callback:

mymodule.page:
  path: '/mymodule/page'
  defaults:
    _title_callback: '\Drupal\mymodule\Controller\MyController::title'
    _controller: '\Drupal\mymodule\Controller\MyController::controller'

And then put the title callback in the controller class, which receives the same parameters as the controller, so that you can determine a title on that information.

  • This only sets the browser/page title, unfortunately. – Deez Nov 10 '16 at 20:58
  • OK, when you already set the title in the route, what you always should do, you can place the title anywhere with the page title block. If you want to show the title in the rendered markup within the controller, then simply put the markup with the h1 tags in the build array. – 4k4 Nov 10 '16 at 21:10
  • I have _title set in the route and the page title block is displayed (it is showing for everything else) but it is still not showing or calling the hook. Will I have to resort to hard coding the title into #markup? return array( '#title' => 'This sets the browser title', '#markup' => '<h1 class="page-header">Hard coded title</h1>This is the html output', ); – Deez Nov 10 '16 at 21:20
  • If you have the #title in the top-level render array that you return, then it should show that. If it doesn't, then there might be a caching or some other problem. Do you see a title at all or not? The page title is a block, are you sure that you don't have some visibility settings configured so it doesn't show for that page? – Berdir Nov 10 '16 at 21:23
  • Double sigh... It was, in fact, ONLY showing for certain content types... ugh. Thank you!!! – Deez Nov 10 '16 at 21:28

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.