Skip to content

Instantly share code, notes, and snippets.

@kevinquillen
Last active April 19, 2018 14:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinquillen/77b4e8915b9894eb1476d610439681d4 to your computer and use it in GitHub Desktop.
Save kevinquillen/77b4e8915b9894eb1476d610439681d4 to your computer and use it in GitHub Desktop.
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.
<?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