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()
?