1

I have a image field (field_image) on my content type. I want to show the image below the header with the node title inside. I am successfully doing that in page.html.twig.

{% if node.field_image %}
  <div id="feature-image">
    <div class="container">
      <h1 class="feature-image">{{ node.label }}</h1>
    </div>
  </div>
{% endif %}

However, the page title is also showing up in the page title block inside of the Header region. I'm trying to find a way to hide the second page title, on the full node view, if the field_image field has a value.

How can I achieve this?

  • node.label has the title of that node!! What value you want to print there instead?? – Razeem Ahmad Apr 5 '18 at 14:02
  • Yes, I am using {{ node.label }} to print in the #feature-image div. However, it's also showing up in the Page title block. I'd like to hide the block altogether if field_image has a value. – MrPeanut Apr 5 '18 at 14:03
2

This method works for me. (Thanks to kim.kennof on Slack for the assistance.)

In my THEME.theme file:

function THEME_preprocess_page_title(&$variables) {
  if ($node = \Drupal::routeMatch()->getParameter('node')) {
    if ($node instanceof \Drupal\node\Entity\Node) {
      $variables['node'] = $node;
    }
  }
}

Then in page-title.html.twig:

{% if node.field_image is empty %}
  {% if title %}
    <h1{{ title_attributes.addClass('page-header') }}>{{ title }}</h1>
  {% endif %}
{% endif %}
  • 2
    if ($node instanceof \Drupal\node\Entity\Node) would be a lot more robust for the condition – Clive Apr 5 '18 at 14:38
  • @Clive Do you mean instead of if ($node = \Drupal::routeMatch()->getParameter('node'))? – MrPeanut Apr 5 '18 at 16:46
  • 1
    No the inner condition. Better to check that something is the single thing that it should be, rather than isn't all the things it shouldn’t be – Clive Apr 5 '18 at 16:50
  • Ahh, of course, makes sense. Code updated and works great. Thank you! – MrPeanut Apr 5 '18 at 17:06
1

You an add a hook_block_access to a .module file in a custom module.

Include these use statements at the top of the file

use Drupal\node\NodeInterface;
use Drupal\Core\Access\AccessResult;

Then implement your hook like so.

/**
 * Hide page title block when the node being viewed has a hero image.
 *
 * Implements hook_block_access()
 */
function ifde_blog_block_access($block, $op, $account) {
  if ($block->id() == 'REPLACE_WITH_PAGE_TITLE_BLOCK_ID' && $op == 'view') {
    $node = \Drupal::routeMatch()->getParameter('node');
    if ($node instanceof NodeInterface && $node->hasField('field_image') && !empty($node->field_image->getValue())) {
      return AccessResult::isForbidden();
    }
  }
  return AccessResult::neutral();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.