I just had a need to do this as well. The right approach here is to store the image URL of the styled image into a variable (through a preprocess function), and then that variable will be available in your twig file.
I've written a function that will get any field_image file and return the original file name, or if you specify a style name, it will return the URL of the styled image.
Inside my .theme
file:
function MYTHEME_preprocess_node(&$vars) {
//get thumbnail images from field_image
$vars['field_image_url'] = _var_image_url($vars, 'field_image', 'thumbnail');
}
//pull image field URL (original or styled)
function _var_image_url($vars, $field, $style_name = '') {
if (!empty($vars['elements'][$field]['#object'])) {
$fields = $vars['elements'][$field]['#object']->getFields();
$image = $fields[$field]->getValue();
if (!empty($image[0]['target_id'])) {
$file = \Drupal\file\Entity\File::load($image[0]['target_id']);
$uri = $file->getFileUri();
if(!empty($style_name)) {
$url = \Drupal\image\Entity\ImageStyle::load($style_name)->buildUrl($uri);
return $url; //the styled URL
} else {
return file_create_url($uri); //original
}
}
}
return false;
}
Now in my twig file (node.html.twig, since I used the preprocess_node function):
<div class="banner" style="background-image:url({{ field_image_url }}"></div>
This function _var_image_url()
has to be called from the THEME_preprocess_node()
function because it's expecting a certain set up in the first $vars
argument. If you try calling it from preprocess_page
, you would need to modify it.