Skip to content

Instantly share code, notes, and snippets.

@larowlan
Created January 21, 2021 21:31
Show Gist options
  • Save larowlan/1a2fa7d0e7b87ac7ea86deba479368c0 to your computer and use it in GitHub Desktop.
Save larowlan/1a2fa7d0e7b87ac7ea86deba479368c0 to your computer and use it in GitHub Desktop.
Preprocess a layout to work out if its in layout builder UI
<?php
/**
* Implements hook_preprocess_HOOK() for your_layout().
*/
function your_theme_preprocess_your_layout(&$vars) {
// Note this only works for 'defaults'. You could adapt it for OverridesSectionStorage.
// Ascertain if we're in layout-builder edit mode.
$parameters = \Drupal::routeMatch()->getParameters();
$vars['is_layout_builder'] = FALSE;
$cache = new CacheableMetadata();
$cache->addCacheContexts(['route', 'user.permissions']);
$cache->applyTo($vars);
if ($parameters->has('section_storage')) {
try {
$storage = $parameters->get('section_storage');
if ($storage instanceof DefaultsSectionStorage &&
($display = $storage->getContextValue('display')) &&
$display->getTargetEntityTypeId() === 'your_target_entity_type_id' &&
$display->getTargetBundle() === 'your_target_bundle') {
$vars['is_layout_builder'] = TRUE;
}
}
catch (\Exception $e) {
// Gulp.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment