I am rendering a node field (which is an url to an image) in the node template file like bellow

<section class="bg" style="background-image: url({{ file_url(node.field_picture_bg.entity.fileuri) }});">

Works as its supposed to, but i have some logic which tests which exact image field to render and i would like to render the field name from a variable, like so bellow (WHICH DOESNT WORK obviously :) ).

<section class="bg" style="background-image: url({{ file_url(node.MYVARIBLE.entity.fileuri) }});">

Where MYVARIBLE is the name of the field. Is this even possible in twig? I know i can archive this with an conditional clause since there are only 2 possibilities for the field name, but this way is more

1 Answer 1


You can use the variable inside of the method get():

{{ node.get(MYVARIBLE).entity.fileuri }}
  • Yup, that's it. Thanks a bunch. I searched the Twig docs and couldn't find this anywhere.
    – lordZ3d
    Sep 25, 2017 at 21:19
  • You can use all object methods whitelisted in TwigSandboxPolicy. These are for example all named or prefixed get, but not set.
    – 4uk4
    Sep 25, 2017 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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