Skip to content

Instantly share code, notes, and snippets.

@jenitehan
Created September 14, 2017 14:53
Show Gist options
  • Save jenitehan/ecf27c32972df163154cb4768dbd69db to your computer and use it in GitHub Desktop.
Save jenitehan/ecf27c32972df163154cb4768dbd69db to your computer and use it in GitHub Desktop.
Add Drupal image template suggestions by bundle and field.
<?php
/**
* Implements hook_theme_suggestions_HOOK_alter().
*/
function THEME_theme_suggestions_image_alter(&$suggestions, $variables) {
// Get the directory and filename.
// Need to use dir and filename to form the URI, since trying to load the file by filename alone
// will skip files that might have been uploaded with the same name as another and had "_0" added to the end.
$path = parse_url($variables['uri'], PHP_URL_PATH);
$path = explode('/', $path);
end($path);
$filename_key = key($path);
$dir = $path[$filename_key - 1];
$filename = end($path);
// Load the files and get the node they're used on.
// This is a bit of a cheat since we're assuming it's only on one node.
/* @var \Drupal\file\FileInterface[] $files */
$files = \Drupal::entityTypeManager()->getStorage('file')->loadByProperties(['uri' => 'public://' . $dir . '/' . $filename]);
if ($files) {
$usage = \Drupal::service('file.usage')->listUsage(reset($files));
$usage = reset($usage);
$nid = key(reset($usage));
$node = \Drupal::entityTypeManager()->getStorage('node')->load($nid);
// Add suggestions for each image field on the node.
$fields = $node->getFieldDefinitions();
foreach ($fields as $field) {
if ($field->getType() == 'image') {
$suggestions[] = 'image__' . $node->bundle() . '__' . $field->getName();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment