3

I have a custom block containing a text field and an image field. I would like to render the block so that the image's URL can be defined as a data attribute of the block's wrapper div so that it can be used by a javascript function to create a parallax background effect behind the text field.

If I make a template file block.parallax.html.twig, I am able to render the image HTML.

{{ content.field_parallax_image.0 }}

However If I try to get the actual image URL, nothing is returned

{{ content.field_parallax_image.0['#url'] }}

If I dump the #item keys

{{ dump(content.field_parallax_image.0['#item']|keys) }}

I am able to get target_id, alt, title, width and height values, but I can't find the URL defined anywhere.

I have also tried to see if I could find anything useful in the block preprocess function but the field_parallax_image #url field in the variables is also empty

function mytheme_preprocess_block(&$variables) {
    if( isset($variables['content']['body']['#bundle']) && $variables['content']['body']['#bundle'] == 'parallax'){
        $variables['img_url'] = $variables['elements']['content']['field_parallax_image'][0]['#url'];
    }
}

Is there a way I can get this URL?

10

#url at this stage is not processed yet. This happens later in the image templates.

To get the url in the block template you can access the uri field in the image file entity instead:

{{ file_url(content.field_parallax_image.0['#item'].entity.uri.value) }}

BTW you didn't find this property in the dump output, because it is a computed value to make it easier to handle entity references.

  • This just outputs the root URL of the site, I think this is to do with file_url(). If I try just {{ content.field_parallax_image.0.entity.uri.value }}, nothing is output. – cheesetriple Jan 22 '16 at 16:22
  • I missed the ['#item'], I edit the answer – 4k4 Jan 22 '16 at 16:26
  • Thanks, 4K4! This rescued me after a long, fruitless session of trial-and-error. Question is, in what documentation does one look to figure out this kind of thing? – Marshall Morrise Mar 7 at 22:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.