1

Drupal 8 file entity full display mode apparently uses the word 'File' for both page title and window title. Yuck.

I've reviewed the various answers on this question, but I'm not seeing a definitive or ideal answer to this specific case. I do have a working solution based on a few answers there, but I don't like it so much. (It's very possible I've overlooked some key bit of insight from that post).

/**
 * Implements hook_page_attachments_alter().
 *
 * @see mymodule_file_view_alter()
 */
function mymodule_page_attachments_alter(array &$page) {

  // Use the file name as the window title.
  if ($entity = \Drupal::routeMatch()->getParameter('file')) {
    $title = $entity->getFilename() . ' | ' . \Drupal::config('system.site')->get('name');
    $page['#attached']['html_head'][] = [
      [
        '#tag' => 'title',
        '#value' => $title,
      ],
      'title'
    ];
  }
}

/**
 * Implements hook_ENTITY_TYPE_view_alter().
 *
 * @see mymodule_page_attachments_alter()
 */
function mymodule_file_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display) {
  // Use the file name as the page title.
  $build['#title'] = $entity->getFilename();
}

I would love to be shown that there is a way to both alter the window title and the page title cleanly from one single piece of code, without for example, getting into the yuckiness of reimplementing the vertical pipe and site name suffix of the window title in my own code. Maybe some sort of route alter or subscriber?

Your Answer

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

Browse other questions tagged or ask your own question.