简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM