Skip to content

Instantly share code, notes, and snippets.

@rikki-iki
Last active February 7, 2023 01:47
Show Gist options
  • Save rikki-iki/f07f9a741597dfabecfd6f88ba69d435 to your computer and use it in GitHub Desktop.
Save rikki-iki/f07f9a741597dfabecfd6f88ba69d435 to your computer and use it in GitHub Desktop.
Useful preprocess theme functions (may use deprecated php)
<?php
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Template\Attribute;
use Drupal\Core\Url;
use Drupal\node\NodeInterface;
use Drupal\Core\Link;
/**
* Implements hook_preprocess_page() for page.html.twig.
*/
function THEME_preprocess_page(array &$vars): void {
// 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(array &$vars): void {
$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() . $referenced_url, [
'attributes' => [
'class' => ['button'],
]
]));
// Create a var to use in the template.
$vars['link'] = $link->toString();
}
}
/**
* Implements hook_preprocess_field().
*/
function THEME_preprocess_field(array &$vars): void {
$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(array &$vars): void {
$vars['block_content'] = $vars['elements']['content']['#block_content'] ?? NULL;
// 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.
$block_id = $vars['attributes']['id'] ?? NULL;
$vars['content']['#attributes']['block_id'] = $block_id;
// Pass the region through to the content.
$region = $vars['elements']['#region'] ?? NULL;
$vars['content']['#attributes']['region'] = $region;
$provider = $vars['elements']['#configuration']['provider'] ?? NULL;
$bundle = $vars['elements']['#bundle'] ?? NULL;
}
/**
* Implements hook_preprocess_maintenance_page().
*/
function THEME_preprocess_maintenance_page(array &$vars): void {
$vars['title'] = t('Temporarily down for maintenance');
}
/**
* Implements hook_form_alter().
*/
function THEME_form_alter(&$form, $form_state, $form_id): void {
// 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(array &$vars): void {
$route = \Drupal::routeMatch()->getRouteObject();
$title = NULL;
if ($route) {
$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)
->addCacheContexts(['route'])
->applyTo($vars);
}
/**
* Implements hook_preprocess_HOOK() for menu.html.twig.
*/
function THEME_preprocess_menu(array &$vars): void {
// Add the menu label as a variable.
$vars['menu_label'] = \Drupal::entityTypeManager()->getStorage('menu')->load($vars['menu_name'])->label();
}
/**
* Implements hook_preprocess_HOOK() for pager.html.twig.
*/
function THEME_preprocess_pager(array &$vars): void {
// Remove html characters for Previous/Next buttons.
if (isset($vars['items']['previous']['text'])) {
$vars['items']['previous']['text'] = t('Previous');
}
if (isset($vars['items']['next']['text'])) {
$vars['items']['next']['text'] = t('Next');
}
$pager = \Drupal::service('pager.manager')->getPager($vars['pager']['#element']);
$vars['total'] = $pager->getTotalPages();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment