Search code examples
twigblockdrupal-8

Drupal Page Title Block


Today I've try to add image_field in "Page Title" block.

I don't know if it's possible ?

If it isn't possible, it is possible to add field_image in twig template ?

Tnks.


Solution

  • The below may help you. First im adding a theme suggestion for page_title, so that i can control the place where i have to over ride the template. I am adding node_type - as suffix to the template.

    Then i am adding the preprocess function- make sure you replace the signature with the type you want "news" at the end should be replaced with your content type from the first function.

    In the second function i am fetching a field called subtitle, and adding the value to variables so that it is available in the template.

    function mytheme_theme_suggestions_alter(array &$suggestions, array &$variables, $hook) {
      if($hook === 'page_title') {
        if($node = \Drupal::routeMatch()->getParameter('node')){
            $node_type = $node->getType();
            // suggestion must use _ and __ as per convention.
            $suggestions[] = 'page_title__'.$node_type;
        }
      }
    }
    
    
    function mytheme_preprocess_page_title__news(&$variables) {
    
      if ($node = \Drupal::routeMatch()->getParameter('node')) {
        try {
          if ($node->get('field_subtitle') && !$node->get('field_subtitle')->isEmpty()) {
            $variables['sub_title'] =
              $node->get('field_subtitle')
                ->get(0)
                ->get('value')
                ->getValue();
          }
        }catch(Exception $e){
    
          \Drupal::logger('mytheme')->error($e);
        }
      }
    }
    

    Now in the template you will sub_title available in the template file, in my case it was page-title--news.html.twig - copied from page-title.html.twig and added respective variable.