Hook a twig template to a block in Drupal 8

1.2k Views Asked by At

I created a module which creates a custom block :

<?php
/**
 * Provides a 'SLS Block' Block
 *
 * @Block(
 *   id = "SLS-Subheader",
 *   admin_label = @Translation("SLS Subheader"),
 * )
 */

namespace Drupal\subheader\Plugin\Block;

use Drupal\Core\Block\BlockBase;

class SubheaderBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {


    return array(
      '#title' => "test",
    );
  }
}
?>

The module name is "subheader"

In my subheader.module i want to hook a specific template:

<?php
/**
 * Implements hook_theme().
*/

function subheader_theme() {
  return array(
    'slssubheader' => array(
      'variables' => array('pierre' => NULL),
      'template' => 'specifictemplate',
    ),
  );
}

I tried all kind of naming convention for the function name and the array key, but always unsuccesful. It never hook the template to specifictemplate.html.twig

Anyone has an idea??

Thanks a LOOOOTTT

Pierre

1

There are 1 best solutions below

0
On

I had the same problem, though probably a different cause. Google lead me to your question though. The issue with your code is the missing #theme key in your build method I believe:

public function build() {
    return array(
      '#title' => "test",
      '#theme' => 'slssubheader' // this one
    );
}

In my case I had to search for a couple of hours before I found out I accidentally added a custom namespace to my .module file. Drupal doesn't like that and didn't recognize any of my hooks.