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

Null-coalescing does not work when method returns null #4499

Closed
norkunas opened this issue Dec 12, 2024 · 4 comments · Fixed by #4500
Closed

Null-coalescing does not work when method returns null #4499

norkunas opened this issue Dec 12, 2024 · 4 comments · Fixed by #4500

Comments

@norkunas
Copy link

norkunas commented Dec 12, 2024

{{ something.nice(category) ?? 'nope' }}

should return nope but the result is empty

tried to add a test to tests/IntegrationTest.php but not sure how to inject an object for tests/Fixtures/tests/null_coalesce.test

this broke my code after latest release: i had a function where it accepts only string type but then the null coalesce stopped working and null was passed instead of the fallback string

@fabpot
Copy link
Contributor

fabpot commented Dec 12, 2024

Can you share a small reproducer? Or at least, tell me if category exists, and the nice() call return value.

@fabpot
Copy link
Contributor

fabpot commented Dec 12, 2024

Can you share a small reproducer? Or at least, tell me if category exists, and the nice() call return value.

I think I know: the method and argument does exist, and the method returns an empty string or null. It should then return nope but it returns an empty string instead.

@azlotnikov
Copy link

It can be reproduced when object getter is used. Here is example:

require_once 'vendor/autoload.php';

class SomeClass {
    private ?string $var = null;

    public function getVar(): ?string {
        return $this->var;
    }
}

$loader = new \Twig\Loader\FilesystemLoader('templates');
$twig = new \Twig\Environment($loader);

$a = new SomeClass();

echo $twig->render('test.twig', [
    'a' => $a,
]);
{{ a.var ?? 123 }}

Twig 3.17 Output:


Twig 3.16 Output:

123

@fabpot
Copy link
Contributor

fabpot commented Dec 12, 2024

New release published.

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

Successfully merging a pull request may close this issue.

3 participants