0

We created custom theme suggestion for fields links using this code

function THEME_theme_suggestions_file_link_alter(array &$suggestions, array $variables) {
  $route = \Drupal::request()->attributes->get('_route');
  // Adds a template suggestion for all files displayed as links, except in node/add and edit forms
  if ( strpos($route, 'add') === FALSE && strpos($route, 'form') === FALSE ) {
    $custom_suggestions[] = 'file_link__button';
  }
}

This allows us to use template_preprocess_file_link() to add more attributes to the file (MIME, weight, description...) like this :

/**
 * Prepares variables to recreate link in file-link--button.html.twig
 * file name & uri, formatted type (with user friendly names) & weight
 *
 */
function THEME_preprocess_file_link__button(&$variables, $hook) {
  // Define user-friendly MIME types name
  $mimes_types_name = [
    'application/vnd.ms-excel' => 'Excel',
    'application/pdf'          => 'PDF',
    // ...
  ];
  $file = $variables['file'];
  $file_type = $file->getMimeType();
  $variables['file_type'] = $file_type;
  if (isset($mimes_types_name[$file_type])) {
    $variables['file_type_formatted'] = $mimes_types_name[$file_type];
  }
  // ...
}

However in none of those function we can access the field name or better its parent to make a dedicated Twig template depending on paragraph parent or field machine name.
In THEME_theme_suggestions_file_link_alter() we could targetthe node type (using the route) but we're using paragraphs and we can't access the parent paragraph.

Any suggestion to make more than one Twig template for template_preprocess_file_link() ?

2
  • The only options available to you are what you will be able to cobble out of $variables.
    – Kevin
    Jul 11, 2020 at 0:13
  • Another option would be to preprocess it at the field level using template_preprocess_field. From there you'll have access to the parent. Better yet, IMO, would be to do extend the file link formatter and do all of this in there.
    – sonfd
    Jul 11, 2020 at 10:13

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.