Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Empty post collection is true inside twig if statement #2914

Open
rubas opened this issue Feb 7, 2024 · 1 comment
Open

[BUG] Empty post collection is true inside twig if statement #2914

rubas opened this issue Feb 7, 2024 · 1 comment

Comments

@rubas
Copy link
Contributor

rubas commented Feb 7, 2024

Expected Behavior

{% set posts = get_posts({'post_type': 'not_existing'}) %}

{% if posts %}
  This is false
{% endif %}

{% if posts is not empty %}
  This is false
{% endif %}

Actual behavior

{% set posts = get_posts({'post_type': 'not_existing'}) %}

{% if posts %}
  This is true
{% endif %}

{% if posts is not empty %}
  This is false
{% endif %}

Notes

An empty array is falsy in PHP, which allow's Twig's if to tests if an array is empty Doc. This doesn't work, if you have a lazy Post Collection (get_posts) and not an array.

You need to use length or empty to check the Post Collection in Twig.

Solution

I don't see a way to improve this currently as the RFC for falsifable is not implemented - except to return an empty array if the post collection is empty (found_posts == 0).

I suggest updating the docs in the meantime with an example as this is not obvious and can lead to bugs.


What version of Timber are you using?

2.0

What version of WordPress are you using?

6.2

What version of PHP are you using?

8.1

How did you install Timber?

Installed or updated Timber through Composer

@rubas rubas changed the title [DOC] Empty post collection is true inside twig if statement [DOCS] Empty post collection is true inside twig if statement Feb 7, 2024
@rubas rubas changed the title [DOCS] Empty post collection is true inside twig if statement [BUG] Empty post collection is true inside twig if statement Feb 7, 2024
@rubas
Copy link
Contributor Author

rubas commented Feb 8, 2024

We fixed the issue with a simple wrapper function.

public static function get_posts(array|false $query = false, array $options = []): null|PostCollectionInterface
  {
    $posts = Timber::get_posts($query, $options);

    if ($posts instanceof \Countable && 0 === \count($posts)) {
      return null;
    }

    return $posts;
  }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants