1

I appreciate that this requirement might be fairly uncommon, and perhaps against the pure Drupal approach, but I'd like to pass additional variables to my field template, from another twig template.

In order to fulfil this requirement, I created a twig function to add additional properties to my field array (I didn't use the default twig merge() function as it destroys the objects in the field array). So, in my template is something like this:

{{ safe_merge(content.body, {'#my_property': 'my_value'}) }}

I then tried to use the template_preprocess_field() function, to check for and set these additional properties as a variable in the twig template - but I believe this hook runs prior to template being built, not as it is built, which is what I had assumed. So my custom properties are not present.

Is there any way to achieve what I'm looking to do?

Update: it seems I was wrong, the added properties are there, under $variables['element'] in my hook. Unfortunately, I need to pass variables to the title field template too - but label at least does appear to be processed prior to being displayed in the template.

  • In the field preprocess hook, did you check the field's render element? Most likely the value would show up in $variables['element']['#my_property'] – 4k4 May 24 '17 at 13:35
  • @4k4 I was just about to update my question - you're right, it is there. So, it's now working as expected with one exception - the node title (label in the template)...it doesn't work for this. Is there a different way I can reference this, and have it work? (I realise why it's not part of content). – user34185 May 24 '17 at 13:53

Your Answer

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