Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Another theme example - preprocessing fields on a paragraph. Formats links with SVG icons next to the title value. FormattableMarkup creates a markup for each link which is being passed as a new variable into the template. This could also be done via hook_preprocess_field, but demonstrates that you can do this from other preprocess hooks.
<?php
/**
* Implements hook_preprocess_paragraph().
*/
function mytheme_preprocess_paragraph(&$variables) {
$paragraph = $variables['elements']['#paragraph'];
$bundle = $paragraph->getType();
if ($bundle == 'fancy_links') {
$variables['fancy_links'] = NULL;
if (!$paragraph->get('field_link')->isEmpty()) {
$links = $paragraph->get('field_link')->getValue();
foreach ($links as $link) {
$external = UrlHelper::isExternal($link['uri']);
// The two SVG icons are different. I removed them from the gist because they are rather large.
if (!$external) {
$url = Url::fromUri($link['uri'])->toString();
$classes = 'hl__fancy-link';
$icon = '<svg [attributes redacted for readability]"/>...</svg>';
}
else {
$url = $link['uri'];
$classes = 'hl__fancy-link hl__fancy-link--external';
$icon = '<svg [attributes redacted for readability]"/>...</svg>';
}
$variables['fancy_links'][] = new FormattableMarkup('<a href="@url" class="' . $classes . '" title="@title"><span class="hl__button__text">@title</span><span class="hl__button__icon hl__button__icon--right">' . $icon . '</span></a>', [
'@url' => $url,
'@title' => $link['title'],
]);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment