0

In the code given below

content.field_image_link[0]['#url']
is empty but it still enters the if condition and adds html
what is incorrect in the below code due to which it enters the if
condition whereas it should enter the second if condition given below

{% if content.field_image_link[0]['#url'] %}

{% block paragraph %}    

 <div{{ attributes.addClass(classes) }}>

    {% block content %}    

{% if content.field_image_link[0]['#url'] %}

<a href="{{ content.field_image_link[0]['#url'] }}">

{{ content.field_image_2 }}
</a>       
<h2>
<a href="{{ content.field_image_link[0]['#url'] }}">
{{ content.field_image_link[0]['#title'] }}
</a>
</h2>
{% endif %}
{% if content.field_image_link[0]['#url'] == '' %}
{{ content.field_image_2 }}
<h2>                                                                                                                                                                                                     
{{ content.field_image_link[0]['#title'] }}                                                                                                                                                               
</h2>
{% endif %}
    {% endblock %}
  </div>

{% endblock paragraph %}
0

2 Answers 2

1

If they are suppose to be mutually exclusive shouldn't you have an if/else statement?

In any case, Testing for an empty value can be a pain with twig.

See this answer

Short answer, based on above link:

{% if content.field_image_link[0]['#url']|render|striptags|trim %}

You want to render to get the field then remove/trim whitespace.

2

You need to check if variable is defined (defined in twig) and additionally also check the length of variable in twig.

{% if content.field_image_link[0]['#url'] is defined and content.field_image_link[0]['#url'] | length > 0 %}
    //do stuff
{% else %}
    //do another stuff
{% endif %}

Not the answer you're looking for? Browse other questions tagged or ask your own question.