Skip to content

Instantly share code, notes, and snippets.

@tmlangley
Last active October 5, 2016 23:20
Show Gist options
  • Save tmlangley/b127c6fa3c3a257535ec48f488078480 to your computer and use it in GitHub Desktop.
Save tmlangley/b127c6fa3c3a257535ec48f488078480 to your computer and use it in GitHub Desktop.
Get inline style for entity field
<?php
function themekit_preprocess_paragraph(&$variables) {
$paragraph = $variables['paragraph'];
$bundle = $variables['paragraph']->bundle();
switch ($bundle) {
case 'simple_small_cta':
$variables['image_inline_style'] = themekit_get_entity_image_inline_style($paragraph, 'field_image', 'small_cta');
break;
case 'simple_large_cta':
$variables['image_inline_style'] = themekit_get_entity_image_inline_style($paragraph, 'field_image', 'large_cta');
}
}
function themekit_get_entity_image_inline_style($entity, $field_name, $image_style) {
$rendered_style = '';
if (!$entity->$field_name->isEmpty()) {
$file_entity = $entity->get($field_name)->entity->get('field_image')->entity;
if ($url = themekit_get_image_style_url($file_entity, $image_style)) {
$rendered_style = 'style="background-image: url(' . $url . ');"';
}
}
return $rendered_style;
}
function themekit_get_image_style_url(File $file, $image_style) {
$uri = $file->getFileUri();
$url = ImageStyle::load($image_style)->buildUrl($uri);
return $url;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment