Skip to content

Instantly share code, notes, and snippets.

@gorkdesign
Forked from rikki-iki/drupal-preprocess.theme
Created September 30, 2022 08:59
Show Gist options
  • Save gorkdesign/0102c023854b79cc56803d2d1c52bab4 to your computer and use it in GitHub Desktop.
Save gorkdesign/0102c023854b79cc56803d2d1c52bab4 to your computer and use it in GitHub Desktop.
/**
* 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');
}
/**
* 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;
}
}
/**
* Implements hook_preprocess_field().
*/
function THEME_preprocess_field(&$vars, $hook) {
$name = $vars['element']['#field_name'];
$bundle = $vars['element']['#bundle'];
$view_mode = $vars['element']['#view_mode'];
if ($name === 'field_suburb') {
// Add a value 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'] = 'My suburb';
}
}
/**
* Implements hook_preprocess_HOOK() for Block document templates.
*/
function THEME_preprocess_block(&$vars) {
$bundle = NULL;
$block_id = $vars['elements']['#id'];
$is_front = \Drupal::service('path.matcher')->isFrontPage();
$provider = $vars['elements']['#configuration']['provider'];
if ($provider === 'block_content' &&
isset($vars['elements']['content']['#block_content']) &&
($block_entity = $vars['elements']['content']['#block_content']) &&
$block_entity instanceof BlockContentInterface) {
$bundle = $block_entity->bundle();
}
// Hide the default homepage content.
if ($block_id === 'wcc_theme_content' && $is_front) {
$vars['content'] = [];
$vars['attributes']['class'] = 'visually-hidden';
}
// Get the value of a field.
if ($bundle === 'basic') {
$vars['suburb'] = $block_entity->get('field_suburb')->value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment