MMPL1
MMPL1

Reputation: 543

Twig - print array without empty values

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?

Upvotes: 3

Views: 3489

Answers (2)

Yassine CHABLI
Yassine CHABLI

Reputation: 3714

You can just add a simple test in your template :

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

      </li>
   {% endif %}
{% endfor %}

Generally speaking , "0"|trim expression will evaluates to false.

Upvotes: 0

Kyrre
Kyrre

Reputation: 698

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.

Upvotes: 6

Related Questions