Drupal 8: Theming a File Link by Content Type

Here's a basic overview and example fo theming a Drupal file link by content type.

  • Enable Twig debugging
  • Create a hook theme suggestions preprocess function
  • Get the node object within the theme hook.
  • Craft the theme hook suggestion to get a template name with the node type in it.

Once we have Twig debugging enabled, inspect the file link. As a default for file_link, I see:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'file_link' -->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/field/file-link.html.twig' -->

In my case, I use Classy as a base theme for my sub-theme, thus the classy path above. but what is missing here is any useful theme hook suggestions out of the box. Next we will remedy that.

Since we are given the theme hook name above, I can craft the theme hook suggestion based on that and by getting the node type and incorporating it into the theme hook suggestion. (see function hook_theme_suggestions_HOOK_alter)

My theme hook alter then would be:

  function MYTHEME_theme_suggestions_file_link_alter(&$suggestions, $vars, $hook) {

  // Get the node type.
  $node = \Drupal::routeMatch()->getParameter('node');
  $type = $node->getType();

  // Create the theme hook suggestion. 
  $suggestions[] = 'file__link__' . 'type_' . $type;
}

Once I do this and drush cr, I will see my new theme hook template suggestion as such:

<!-- THEME DEBUG -->
    <!-- THEME HOOK: 'file_link' -->
<!-- FILE NAME SUGGESTIONS:
   * file--link--type-news.html.twig
   x file-link.html.twig
-->

In my case, my node type is "News" and you can see that in the template suggestion name:

file--link--type-news.html.twig