Score:-1

Get the value of a field to do an if statement Twig

id flag

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

MrD avatar
cn flag
MrD
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.
Monster971 avatar
id flag
Thank you for your quick reply. {% if (content.field_custom|striptags) == 'John' %} That didn't work for me though unfortunately. How to use it ?
Kevin avatar
in flag
Because it is not a string, it is a render array. It will never just equal John.
MrD avatar
cn flag
MrD
try with content.field_custom|render|striptag or just node.field_custom.value
Monster971 avatar
id flag
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?
Score:1
in flag

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! :)

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.