0

I'm looking to have a page on /templates/header which only renders what there is in the header region of the theme. I am using the following code for a custom controller.

namespace Drupal\wco_drupal_module\Controller;

use Drupal\Core\Controller\ControllerBase;

/**
 * Templates controller.
**/
class TemplatesController extends ControllerBase {

  public function header() {
    return [
      '#theme' => 'wco_templates_header',
    ];
  }

}

In the wco_drupal_module.module file, I am using the following code.

function wco_drupal_module_theme($existing, $type, $theme, $path) {
  return [
    'wco_templates_header' => [
      'render element' => 'requirements',
      'template' => 'region--header',
      'path' => $theme . '/templates/layout',
    ],
  ];
}

The region-header.html.twig template file contains the following code.

<h1>tasty test</h1>
{% if content %}
  <div class='flex-column region-headerW' >
    <div class='region region-header maxwidth' >
      {{ content }}
    </div>
  </div>
{% endif %}

This renders something, but there are two problems:

  • The content is missing, so I only see tasty test.
  • This is all rendered inside the generic layout; rather than just showing the header, I'm showing a whole page with header, footer, and all the regions.

I want to avoid that, and only display a single region (header) on a path. How can I achieve that?

1
  • You want to generate a block and not a page if I understand correctly? But in this case you won't have a path. Do you want a path with only the contents of your controller? Commented Nov 3, 2023 at 17:45

1 Answer 1

2

Display a single region, header, on a path:

  1. create path : for this either can add node page with specific path or add custom controller
  2. View the path let say /header
  3. Then override the page template with specific path as displayed in the inspect provided by theme suggestion for eg override file name: page--testing--abc.html.twig Reference link for enable theme suggestion
  4. Then open the override file in editor & keep the required region: like in my scenario: {{ page.header }}

Note: Make sure in the backend if you added additional block in the same region(header) then that 'll start appearing so hide other blocks for this particular page or either add new region and add that region in override template , add header block of site from backend in newly added region

2
  • 1
    Fantastic, super simple. thank you! Commented Nov 4, 2023 at 14:54
  • 1
    Yeah it's pretty easy approach, handling things at theme level your welcome ;) Commented Nov 4, 2023 at 15:27

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.