Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save algotrader-dotcom/d1f9112ba9880fcb94a9ef1a59239cff to your computer and use it in GitHub Desktop.
Save algotrader-dotcom/d1f9112ba9880fcb94a9ef1a59239cff to your computer and use it in GitHub Desktop.
use Drupal\node\NodeInterface;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;
/**
* Implements hook_preprocess_page() for page.html.twig.
*/
function THEME_preprocess_page(&$vars) {
// Add sitename and slogan to page.
$vars['site_name'] = \Drupal::config('system.site')->get('name');
$vars['site_slogan'] = \Drupal::config('system.site')->get('slogan');
// Do things based on route.
$route_match = \Drupal::routeMatch();
$current_route = $route_match->getRouteName();
$current_path = \Drupal::service('path.current')->getPath();
switch ($current_route) {
case 'system.401':
case 'system.403':
$vars['title'] = t('Access denied');
break;
case 'system.404':
$vars['title'] = t('Page not found');
break;
}
// Do things based on the node.
if (($node = $route_match->getParameter('node')) && $node instanceof NodeInterface) {
// Set a global var we can use when viewing a node.
$vars['is_node'] = TRUE;
$vars['type_class'] = 'page-type--' . strtr($node->getType(), '_', '-');
if ($node->getType() === 'article') {
// Add created date when viewing an article node.
$vars['created_date'] = \Drupal::service('date.formatter')->format($node->getCreatedTime(), 'medium'),
// Add the author when viewing an article node.
$uid = $node->getOwnerId();
$vars['author'] = \Drupal::entityTypeManager()->getViewBuilder('user')->view($uid, 'compact');
// Or just their name.
$user = \Drupal\user\Entity\User::load($uid);
$vars['author'] = $user->getDisplayName();
// Render node header_image.
$vars['header_image'] = \Drupal::entityTypeManager()->getViewBuilder('node')->view($node, 'header_image');
}
}
}
/**
* Implements hook_preprocess_node().
*/
function THEME_preprocess_node(&$vars) {
$node = $vars['elements']['#node'];
$view_mode = $vars['elements']['#view_mode'];
$type = $node->getType();
// Check if field has value.
if ($node->hasField('field_suburb') && !$node->field_suburb->isEmpty()) {
$vars['attributes']['class'][] = 'has-suburb';
// Get field value (if normal field)
$vars['suburb'] = $node->get('field_suburb')->value;
// Get referenced entity (if entity ref field)
$vars['suburb'] = $node->get('field_suburb')->entity;
}
// Make a new link from an entity reference and plain text field.
// So the editor can customise the link text.
if ($node->hasField('field_reference') && $node->hasField('field_link_label')) {
// Get the URL of the referenced node.
$referenced_url = $node->get('field_reference')->entity->toUrl()->getInternalPath();
// Get the value of the label field.
$label = $node->get('field_link_label')->value;
// Create the link.
$link = Link::fromTextAndUrl($label,
Url::fromUserInput(base_path() . $references_url, [
'attributes' => [
'class' => ['button'],
]
]));
// Create a var to use in the template.
$vars['link'] = $link->toString();
}
}
/**
* Implements hook_preprocess_field().
*/
function THEME_preprocess_field(&$vars, $hook) {
$name = $vars['element']['#field_name'];
$bundle = $vars['element']['#bundle'];
$entity_type = $vars['element']['#entity_type'];
$field_type = $vars['element']['#field_type'];
// Ds overrides '#view_mode' to '_custom' but keeps the original in '#ds_view_mode'.
$view_mode = isset($vars['element']['#ds_view_mode']) ? $vars['element']['#ds_view_mode'] : $vars['element']['#view_mode'];
if ($name === 'field_suburb') {
// Add a custom variable to a field
$vars['items'][0]['icon_id'] = 'location';
// Add a class to a field
$vars['attributes']['class'][] = 'is-suburb';
// Change it's rendered label
$vars['label'] = t('My suburb');
// Add a class to each item in a field
foreach ($vars['items'] as $delta => $item) {
if ($vars['items'][$delta]['attributes'] instanceof Attribute) {
$vars['items'][$delta]['attributes']->addClass('meta__type');
}
}
}
}
/**
* Implements hook_preprocess_HOOK() for Block document templates.
*/
function THEME_preprocess_block(&$vars) {
// These variables are set in HOOK_theme_suggestions_block_alter().
// @see https://gist.github.com/rikki-iki/6fe41e11ac59b3e1d07e#file-drupal-8-theme-suggestions-theme-L7
// Pass the block_id through to the content.
if (isset($vars['attributes']['id'])) {
$vars['content']['#attributes']['block_id'] = $vars['attributes']['id'];
}
// Pass the region through to the content.
if (isset($vars['elements']['#region'])) {
$vars['content']['#attributes']['region'] = $vars['elements']['#region'];
}
$block_id = $vars['attributes']['id'];
$provider = $vars['elements']['#configuration']['provider'];
if (isset($vars['elements']['#bundle'])) {
$bundle = $vars['elements']['#bundle'];
// Get the value of a field.
if ($bundle === 'basic') {
$vars['suburb'] = $block_entity->get('field_suburb')->value;
}
}
}
/**
* Implements hook_preprocess_paragraph().
*/
function THEME_preprocess_paragraph(&$vars) {
$paragraph = $vars['paragraph'];
$bundle = paragraph->bundle();
if ($paragraph instanceof Paragraph && $paragraph->hasField('field_display') && $paragraph->get('field_display')->value === 'title_summary') {
// Add a class for child displays.
$vars['featured_display'] = 'featured--child';
};
}
/**
* Implements hook_preprocess_maintenance_page().
*/
function THEME_preprocess_maintenance_page(&$vars) {
$vars['title'] = t('Temporarily down for maintenance');
}
/**
* Implements hook_form_alter().
*/
function THEME_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
// Add search placeholder for keywords field.
if ('views_exposed_form' === $form_id) {
$view = $form_state->get('view');
if ($view->id() === 'search') {
$form['#attributes']['class'][] = 'form__search';
$form['query']['#attributes']['placeholder'] = t("How can we help you today?");
}
}
}
/**
* Implements hook_preprocess_breadcrumb().
*/
function THEME_preprocess_breadcrumb(&$vars) {
$route = \Drupal::routeMatch()->getRouteObject();
$title = \Drupal::service('title_resolver')->getTitle(\Drupal::request(), $route);
$vars['breadcrumb'][] = [
'text' => $title,
];
// Adding a dependency on the route actually disables caching for this block
// but that's what we want, to prevent caching issues.
CacheableMetadata::createFromRenderArray($vars)
->addCacheableDependency($route)
->applyTo($vars);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment