0

I need to find out the currently active Twig template from within my module preprocess function.

function mymodule_preprocess_field(&$variables, $hook) {
    // How do i retrieve the currently active Twig template?
}

I need to know whether it is field.html.twig, field--field-example.html.twig or some other template suggestion.

Is that possible?

8
  • 1
    What is the purpose?
    – Kevin
    Aug 15, 2019 at 13:03
  • I'm creating a helper module for TailwindCSS theme. I want to provide the themer with the ability to inject classes into fields without having to override every single template. The idea is that the themer can create a YAML file containing a structured list of classes that I will load in the preprocess and inject. Aug 15, 2019 at 13:15
  • Why would you need the template file name to decide which classes to inject? Wouldn't it make more sense to base it on criteria, like the field name, formatter being used, and so on?
    – Clive
    Aug 15, 2019 at 13:16
  • I want to allow the themer to create a YAML file like this: ibb.co/6rJmwRF Then in my module preprocess, I want to load the YAML file, check whether there is an entry matching the current Twig template and inject the classes. Aug 15, 2019 at 13:23
  • 1
    Oh ok, you can get most of what you need from ThemeManager::render().
    – Clive
    Aug 15, 2019 at 14:05

1 Answer 1

0

With the help of Clive's comment, I managed to identify the active theme suggestion. Code below.

function mymodule_preprocess_field(&$variables, $hook) {
  $theme_suggestions = mymodule_get_theme_suggestions($hook, $variables);

  $active_suggestion = mymodule_get_active_theme_suggestion($theme_suggestions);
}

function mymodule_get_theme_suggestions(String $base_hook, array $variables) {
  // Invoke hook_theme_suggestions_HOOK().
  $suggestions = \Drupal::moduleHandler()->invokeAll('theme_suggestions_' . $base_hook, [$variables]);

  // Invoke hook_theme_suggestions_alter().
  $hooks = [
    'theme_suggestions',
    'theme_suggestions_' . $base_hook,
  ];
  \Drupal::moduleHandler()->alter($hooks, $suggestions, $variables, $base_hook);

  array_unshift($suggestions, $base_hook);

  return $suggestions;
}

function mymodule_get_active_theme_suggestion($suggestions) {

  $theme_registry = theme_get_registry(FALSE);

  // Order by most specific first.
  $suggestions = array_reverse($suggestions);

  foreach ($suggestions as $candidate) {
    if ($theme_registry
      ->has($candidate)) {
      return $candidate;
    }
  }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.