0

I have a taxonomy called Fish and 2 terms in it. Bass and Gold. I have a term reference field on a Page node, and its a select list. The editor can select either Bass or Gold. And I want display something depending on what the user selects. I cannot get it to work. This is what I have tried. Below the Bass tid is '1'.

{% if node.field_term_reference.value == '1' %} <p>The value is Bass</p> {% else %} <p>The value is Gold</p> {% endif %} 

Below I am outputting the string value bass.

{% if node.field_term_reference[0]['#title'] == "bass" %} <p>The value is Bass</p> {% else %} <p>The value is Gold</p> {% endif %} 

Both of these return "The value is Gold" I tried this also

{% if node.field_term_reference.label == "bass" %} <p>The value is Bass</p> {% else %} <p>The value is Gold</p> {% endif %} 

What if you want to add multiple terms and use AND OR "bass" and "finch".

{% if node.field_term_reference.entity.label == "bass" and or "finch" %} 

How would it be written?

1
  • @paulcap1 please stop editing Answers into the question - you can add an answer for that Commented Sep 12, 2017 at 10:17

3 Answers 3

4

The original question is how to use the term id in a twig condition. You find the term id in the property target_id of the reference field:

{% if node.field_term_reference.target_id == '1' %} <p>The value is Bass</p> {% else %} <p>The value is Gold</p> {% endif %} 
1
  • This won't work if there is more than one value for field_term_reference. Only the first target_id in the array is returned by node.field_term_reference.target_id. Commented Jan 28, 2019 at 17:34
2

It's because the value of node.field_term_reference[0]['#title'] in reality it's <div class="something">bass</div>; therefore, your condition is false every time. Same for the other two.

Thus, in your condition you need to get the raw (no markup) value of the field. See How do I get the raw field value in a template?

This should work:

{% if content.field_term_reference.0 == '1' %} <p>The value is Bass</p> {% else %} <p>The value is Gold</p> {% endif %} 
0

I found the answer here if anyone needs it.

{% if node.field_term_reference.entity.label == "bass" %} <p>The value is Bass</p> {% else %} <p>The value is Gold</p> {% endif %} 
4
  • This isn't the term ID? Commented Sep 12, 2017 at 12:08
  • Meaning, the label/name of the term can always change, the term id won't. Soon as the name changes, it breaks the logic. Commented Sep 12, 2017 at 15:43
  • @Kevin, Your right it would be better to use the tid. I tried {% if node.field_term_reference.0 == '1' %} but it always return false? I am not able to even print the tid. Commented Sep 13, 2017 at 10:45
  • @paulcap1, I've added my comment as answer with a code example. Commented Sep 14, 2017 at 21:05

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.