I am trying to have a header with a different image for each page of my site. I believe I should be creating a block. I don’t want to create x blocks for x pages, and I prefer to do it programmatically.
So I developped a block using in SubheaderBlock.php.
/** * Provides a 'SLS Block' Block * * @Block( * id = "subheader", * admin_label = @Translation("slssubheader"), * category = "custom", * ) */ namespace DrupalsubheaderPluginBlock; use DrupalCoreBlockBlockBase; class SubheaderBlock extends BlockBase { /** * {@inheritdoc} */ public function build() { $node = Drupal::routeMatch()->getParameter('node'); if ($node) { $nid = $node->id(); } return array( '#title' => '', '#description' => '', '#nid' => $nid, ); } }
Then, I can use the node ID in the Twig template and change the picture accordingly. The node ID is well passed to the Twig template, but it is cached! So, whenever the page change, {{ #nid }}
outputs the same ID.
I have also tried to change Twig template suggestion and have a Twig template for each page, but still there are same caching problem.
The code below is probably not the perfect one.
/** * @file * Code for the example module. */ /** * Theme hook */ function subheader_theme_suggestions_alter(array &$suggestions, array $variables, $hook) { $twig = 0; // change the suggestion only for the block_id 'subheader' if(isset($variables['elements']['#plugin_id'])){ if ($variables['elements']['#plugin_id']=== "subheader"){ // give the twig template the same ID as the NID $node = Drupal::routeMatch()->getParameter('node'); if ($node) { $twig = $node->id(); } // suggestion pattern is 'block__subheaderID $suggestions[] = $hook . '__' .'subheader'.$twig; }} }
A