0

We have a need to set an element such as <div> to have an image as a background. I am trying to figure out the way to get the image to display as a background but also with the image style that was used.

The image field (field_image) in question is used in multiple view modes with different image styles.

Example:

  1. Basic page view mode: default, field_image with format = image and image style = large
  2. Basic page view mode: promoted, field_image with format = image and image style = small
  3. Basic page view mode: small tile, field_image with format=image and image style = medium

How can I accomplish the code below? Would the proposed solution work as I am not sure it is safe to use ['#markup']?

<div class="wrapper">
  <div class="wrapper__image" style="background-image: url('{{ file_url(node.field_image.entity.uri.value) }}')"></div>
  <div class="wrapper__content">
    <!-- some text here -->
</div>

Currently on View mode:

  1. Field_image with Format = Image, Image Style = large

Current problem:

  1. node.field_image.entity.uri.value returns the original images, not the one where the image style is applied.

Proposed solution:

  1. set format = URL to image
  2. image style = large
  3. update the twig template to use node.field_image.0['#markup]
5
  • @Hudri the problem i have with that question and answer is that it doesn't address the original question. In that question and mine, we need a way to pull the image style in the preprocess hook. The best answer simply puts "myimagestyle" and assumes that the field will always have that image style. That is not the case in my question. I will update it to reflect it Commented Mar 9, 2018 at 16:56
  • What doesn't work with style="background-image: url('{{ content.field_image }}'); in your template?
    – Hudri
    Commented Mar 9, 2018 at 17:27
  • Ah, I guess your issue are the wrapping <div> of the field formatter. You usually can access the raw value of any field by adding the delta to it, e.g. {{ content.field_image.0 }}
    – Hudri
    Commented Mar 9, 2018 at 17:39
  • @Hudri using the raw value returns the original url for the image. When an image style is applied to an image an image is created that is something along the lines of sites/default/files/styles/large/image-url.png. I want to get that URL Commented Mar 9, 2018 at 23:43
  • Use must use the raw (calculated) value of the content render array, not the value from the node entity.
    – Hudri
    Commented Mar 10, 2018 at 9:49

0

Browse other questions tagged or ask your own question.