-1

I am trying to generate a PDF with Entity Print. Until then all is well.

In my Twig page, I try to make conditional displays. But I can’t get the conditions to work.

I render my fields using {{ content.field_custom }} and that also works fine.

But the condition don't work , when I do something like :

{% if content.field_custom == 'John' %} ...

or

{% set field = content.field_custom %}
{% if field == 'John' %}
   <p>Hello</p>
{% endif %}

I need to do this in the fields twig template, can someone help me?

Many thanks

5
  • Your condition not working because content.field_custom value not equal Jonh. variable content.field_name is render array. So all values is includes string of template field render. Examples "<div>Jone</div>". You have to use strip tags for that. or using node.field_name.value for condition. – MrD Jun 15 at 1:09
  • Thank you for your quick reply. {% if (content.field_custom|striptags) == 'John' %} That didn't work for me though unfortunately. How to use it ? – Monster971 Jun 15 at 1:17
  • Because it is not a string, it is a render array. It will never just equal John. – Kevin Jun 15 at 1:36
  • try with content.field_custom|render|striptag or just node.field_custom.value – MrD Jun 15 at 1:39
  • Thank you again for your answer. It seems to be working but I'm still having a problem that I hadn't anticipated. My field is fed one by one token so, node.field_custom.value returns me the token ([current-user: field_custom: value]) and not the value of the token. How to solve this? – Monster971 Jun 15 at 13:34
0

I recommend the Twig Field Value module, which provides a field_value filter that you can apply directly to a field:

{{ content.field_name|field_value }}

Also, while this doesn't specifically answer your question, I would be remiss not to mention the handy and useful Twig Tweak module. It rocks! :)

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.