I want to display a bunch of data inside a view table, where each dataset has up to three different files. The user should be able to download these files by clicking a custom button or image in this table. I already learned that it's really hard or impossible to create different templates for fields of type file (file_link), at least without creating custom modules. For example, one file is from type PDF, and by default, Drupal shows a small PDF icon in front of the file name, and the file size behind. I can completely customize this behavior by editing file-link.html.twig, but this customizes ALL file links in the table, well, on the entire page.

I want to create a custom template for each file, based on their field name, like this: file-link--field--node--field-xyz-pdf.html.twig. I tried to alter theme suggestiongs by hooking into MYMODULE_theme_suggestions_file_link_alter(&$suggestions, $variables) through a custom module, but $variables doesn't contain the original field name or something else unique related to the field.

My next step was trying to hook into MYMODULE_preprocess_file_link(&$variables) and further into MYMODULE_preprocess_views_view_field(&$variables, $hook), finally finding the field name: $variables['field']->field.

But how do I pass this field name back to the theme suggestions hook? Honestly, I'm at my wits' end.

  • You'll want to use "getters" or "magic" methods to get the fields into your custom theme hook. For example, you can do something like this in your hook: if ($node->hasField('field_foo') && !$node->get('field_foo')->isEmpty()). You'd need to define and check for a node around that as well. Once you are within that code, you should be able to get many more variables to use as part of your template naming convention. Commented Mar 5, 2021 at 15:46


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.