Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - print array without empty values

Tags:

loops

php

twig

I have array constructed like this

add_to_context('custom', [
  [
   'title' => 'My title',
   'link' => 'My link'
  ],
  [
    'title' => 'My title 1',
    'link' => 'My link 1'
  ]
]);

and in view I have simple loop

{% for item in custom %}
    <li>
        <h1>{{ item.title }}
        <img src="{{ item.link|e }}" target="_blank">

    </li>
{% endfor %}

And everything works fine. But I want to print elements which have both keys with value. For example, if I have

[
  'title' => '',
  'link' => 'mylink'
]

I don't want to print this. If link will be empty I don't want it too. If both are empty - the same. I want to print it only if both keys have values. So, how can I do this?

like image 261
MMPL1 Avatar asked Sep 24 '26 23:09

MMPL1


1 Answers

You could do something like this, maybe.

Twig even has a little built in functionality for this:

<ul>
    {% for item in custom if item.title and item.link %}
        <li>{{ item.title }}</li>
    {% endfor %}
</ul>

I haven't tested it, but I assume the and in the if statement should work.

like image 51
Kyrre Avatar answered Sep 27 '26 13:09

Kyrre