5

I'm using PhpStorm/xdebug/MAMP to look at the variable I want to access:

enter image description here

I have tried using the following to get at the data:

{% set image_width = content.field_image.0['#item'].values.width %}

and

{% set image_width = content.field_image.0['#item'].values.width.value %}

Neither of these lines produce any data.

Any help is greatly appreciated!

1
  • use hook_preprocess to create variable from the data. twig is not phptemplate engine, so you have to approach it differently than you'd do in d7.
    – user21641
    Sep 14 '17 at 5:41
7

You can't access the array values because it is protected. But you don't need to, because you can get the properties from a field item directly:

{% set image_width = content.field_image.0['#item'].width %}

BTW the content variable is a render array with no fixed structure. The presence and position of #item changes dependent on the field formatter and other core, contrib or custom code.

So it's better to use the entity object, for example the paragraph entity in a paragraph template:

{% set image_width = paragraph.field_image.0.width %}
1
  • {% set image_width = paragraph.field_image.0.width %} works perfectly. Thanks!
    – Sean Jones
    Sep 14 '17 at 17:52
0

If using Media (Drupal 8 or 9), here's an example on how to access the width of the image in a node template:

{% set image_width = node.field_image.entity.field_media_image.0.width %}

Please note that field_image is an Entity Reference to Media.

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.