Various ways of adding classes to anchors, as well as title markup within that anchor, from hook_preprocess_field in Drupal 8. These are all link fields, which do not have a base twig to modify the output of the a tag.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Implements hook_preprocess_field(). | |
*/ | |
function mytheme_preprocess_field(&$variables) { | |
if ($variables['element']['#entity_type'] == 'paragraph' && $variables['field_name'] == 'field_reference_link') { | |
foreach ($variables['items'] as $key => $item) { | |
$variables['items'][$key]['content']['#options']['attributes']['class'][] = 'hl__link-tag'; | |
} | |
} | |
if ($variables['field_name'] == 'field_directions_link') { | |
foreach ($variables['items'] as $key => $item) { | |
$variables['items'][$key]['content']['#options']['attributes']['class'][] = 'hl__link-tag'; | |
} | |
} | |
if ($variables['field_name'] == 'field_my_top_guides') { | |
foreach ($variables['items'] as $key => $item) { | |
$variables['items'][$key]['content']['#options']['attributes']['class'][] = 'hl__link-tag'; | |
$variables['items'][$key]['content']['#options']['attributes']['class'][] = 'hl__link-tag--with-arrow'; | |
$variables['items'][$key]['content']['#title'] = new FormattableMarkup('<span>@title</span>', [ | |
'@title' => $item['content']['#title'], | |
]); | |
} | |
} | |
if ($variables['field_name'] == 'field_external_service_link') { | |
foreach ($variables['items'] as $key => $item) { | |
$variables['items'][$key]['content']['#options']['attributes']['class'][] = 'hl__button'; | |
$variables['items'][$key]['content']['#options']['attributes']['class'][] = 'hl__button--small'; | |
$variables['items'][$key]['content']['#options']['attributes']['class'][] = 'hl__button--minor'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment