I am trying to create a views block that will of a content type and use an image fields value of the node as a background image of a div inside the block's template file. But I cannot get the image file url inside the twig file so that it can be used as background image. Is there any way to get raw values of the field inside twig templates?
3 Answers
Easily done with Paragraphs. Enable and create a paragraph, call it whatever you like (block with background image). You'll want 2 fields, one for the background image and one block reference. Then you can add a layout with 2 regions, one for the background image and one for the block. Update it in the manage display. Then you need to update the basic page and add the paragraph field so you'll have the option of using it on the page.
Otherwise try this code to get the image path:
{{ file_url(element['#object'].field_name.0.entity.uri.value) }}
Just change "field_name" to the machine name for your image.
Similar I tried to use the raw field value of a color-field inside a twig template. First I used the wrong preprocessor, but then I tried hook_preprocess_page. This worked for me.
$variables['bgcolor'] = $variables['node']->field_bgcolor->color;
So if you like to use your variable inside of page.html.twig use
function yourtheme_preprocess_page(&$variables) {
$image_id = $variables['node']->field_yourimagefield->target_id;
$image_file = file_load($image_id);
$image_public_uri = $image_file->getFileUri();
$variables['image_url'] = file_create_url($image_public_uri);
// var_dump($variables['image_url']);
}
Maybe you can shorten it, but this way it's more readable.
Afterwards (after clearing cache) you can access your value inside the twig template
{{ image_url }}