Wed Nov 11 2020

How to Display the Page Title on a Node Using Layout Builder in Drupal 8

I'm working on a Drupal 8 site now that heavily uses layout builder and one of the requirements is to display the page title on some pages and hide it on others. That sounds pretty straightforward since the page title is now a block. Well, layout builder doesn't support display of the page title block at the moment. It will soon, but not yet, and not in Drupal 8.

Since I couldn't just drop the page title block in a layout builder section I had to get creative and come up another way to handle this.

It had to be simple and something the content creator and those who manage the site could easily toggle on and off and display the page title above the layout builder content.

After a bit of UI design and workflow prototyping I settled on creating a toggle in my content type (page) that displayed on the node edit field. I created a boolean field named "Display Page Title" (field_display_page_title) and placed it below the title in my content type's form display.

Page title toggle

Now that the field was there I needed to check for its value and then display the page title or not.

Normally this would require some configuration on the content type's display page but since layout builder is taking over this portion of things I had to create a preprocess function. This preprocess function was simple as I just needed to check for the field and get its value and then pass that over to the content type's custom template file to do something with it.

First I created a preprocess function in my theme's *.theme file. The code here looks for the content type "page" and then sets a variable called "displayPageTitle" for me to use in my template. That variable grabs the value from the field I created earlier (field_display_page_title).

* Implements hook_preprocess_node().
function THEMENAME_preprocess_node(&$variables) {
  switch ($variables['node']->getType()) {
    case "page":
      $variables['displayPageTitle'] = $variables['elements']['#node']->field_display_page_title->value;

Now that the variable is created I can pass that to my template file for the page content type (node--page.html.twig) and check for the value. Then if the checkbox is checked I will display the title, otherwise nothing is displayed.

{% if page %}
  {% if displayPageTitle == 1 %}
    <h1 class="page-title">{{ node.label }}</h1>
  {% endif %}
{% endif %}

This works very well as now I have a single toggle on each node and if the checkbox is checked it will display the page title on the page above the layout builder generated layout.