How to check if there is a record in the response TWIG - data in table format

I have a multidimensional array where some objects exist and others do not. All data was used on the page. Then I plan to test it at TWIG. data examples:

array:2[
  0 => Data1 {
    -id: 17
    -porodType: "1d"
    -name: "Dally promotion" 
  }
  1 => Data1 {
    -id: 34
    -porodType: "S"
    -name: "Special" 
  }    
]

      

How do I check if an entry exists with porodType = "1d" in response? How to display a different message for this operation: exist (OK) / no-exist (ERROR)?

When registering TWIG:

{% for d in Data1 %}
    {% if d.porodType == '1d' %}
        <button class="btn">OK</button>
    {% else %}
        <button class="btn"">Error</button>
    {% endif %}
{% endfor %}

      

this code result: <button class="btn">OK</button><button class="btn">Error</button>

but i expected <button class="btn">OK</button>

or<button class="btn">ERROR</button>

+3


source to share


2 answers


If you only want to show one button, you will need to track down the flag error, as you cannot break loops in Twig

,



{% set error = false %}
{% for d in Data1 %}
    {% if d.porodType != '1d' %}
        {% set error = true %}
    {% endif %}
{% endfor %}
{% if error %}
    <button class="btn">Error</button>
{% else %}
    <button class="btn">OK</button>
{% endif %}

      

+3


source


Using twig for..if..else might be simpler than the currently accepted answer:

{% for d in Data1 if d.porodType == "1.d" %}
<!-- show error button -->
{% else %}
<!-- show the okay button -->
{% endfor %}

      



The else clause runs when the loop was empty (there were no iterations).

See the documentation for the tag: https://twig.sensiolabs.org/doc/2.x/tags/for.html

+2


source







All Articles