0

Is it possible to use twig template naming conventions to target a field on the front page only? For example, if I want a different version of the header field on my front page I could use field--node--field-header-page-front.html.twig

1 Answer 1

0

Add this code to your mytheme.theme file

/**
 * Implements hook_theme_suggestions_HOOK_alter() for field templates.
 */
function mytheme_theme_suggestions_field_alter(array &$suggestions, array $variables) {
  // Check if it's the front page.
  if (\Drupal::service('path.matcher')->isFrontPage()) {
    $field_name = $variables['element']['#field_name'];
    // Add a template suggestion for the all node fields on the front page.
    $suggestions[] = 'field__node__' . $field_name . '__front_page';
  }
}

Results in:

6
  • Thanks but I added this and I don't see this:
    – Sam
    Dec 6, 2023 at 15:11
  • Only seeing the original: <!-- FILE NAME SUGGESTIONS: * field--node--field-header--page.html.twig x field--node--field-header.html.twig * field--node--page.html.twig * field--field-header.html.twig * field--string.html.twig * field.html.twig -->
    – Sam
    Dec 6, 2023 at 15:11
  • Did you rename the ‘mytheme’ part in the function’s name to your actual theme’s machine name?
    – No Sssweat
    Dec 6, 2023 at 21:41
  • Yes, it matches with my theme name
    – Sam
    Dec 7, 2023 at 13:13
  • And you flushed the cache?
    – No Sssweat
    Dec 7, 2023 at 13:33

Your Answer

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

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