0

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

2

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

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

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.