Skip to content

Instantly share code, notes, and snippets.

@kevinquillen
Last active Apr 19, 2018
Embed
What would you like to do?
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