3

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?

8
  • 3
    Twig can check if a value is empty. See here. All you need after that is a simple if. Commented Mar 8, 2019 at 8:16
  • So I need to check if my 'item' is empty inside for loop but before printing <li> element, right? Commented Mar 8, 2019 at 8:18
  • Your item will still have content in the example you showed us. It's the 'item.title' you want to check. Commented Mar 8, 2019 at 8:20
  • 1
    Yes, that's correct. Something along the lines of {% if item.title is not empty && item.link is not empty %} .... Ofc if you want more validation you can also check if defined, although it's not really necessary if you're absolutely sure that the values exist. Commented Mar 8, 2019 at 8:22
  • 1
    @DarkBee, Andrei ahhh, my mistake. I have typo error. Now it works like it should. Thanks again Commented Mar 8, 2019 at 8:40

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work. Twig error: Unexpected token "name" of value "if" ("end of statement block" expected).
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.