Last active
April 19, 2018 14:35
-
-
Save kevinquillen/959fa7d98089881b2da502c2d4355178 to your computer and use it in GitHub Desktop.
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.
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_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