We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

VOLT: default filter is not working with booleans (by design)

Hi all,

after some illogical results in my templates I've made a short test snippet which I think should produce a different result:

a.html.volt

{% include 'b.html' with [ testVar : false ] %}

b.html.volt

{{ dump(testVar) }}
{{ dump(testVar|default(true)) }}

Rendering A will then produce:

bool(false) bool(true)

According to phalcon documentation it's behaving as expected:

Sets a default value in case that the evaluated expression is empty (is not set or evaluates to a falsy value)

How can I accomplish what my code is trying to do? I need to be sure that, even if not defined, testVar, should be evaluated as a bool, defaulting to true.

Thanks Gianluca



20.4k
Accepted
answer
edited Jul '14

I've actually fit my needs with a custom filter:

$volt->getCompiler()->addFilter('def',  function($args_list) use ($di) {
        $args = explode(", ", $args_list);
        return "(isset($args[0]) ? $args[0] : $args[1])";
});

Now the result is: bool(false) bool(false)

If someone can contribute with better code or solutions would be very appreciated. Regards Gianluca



98.9k

You can use 'defined':

{{ dump(testVar is defined ? testVar : true) }}


20.4k
edited Jul '14

Thanks Phalcon for the suggestion! So it should be:

{% if testVar is defined ? testVar : true %}

My solution looks like:

{% if testVar|def(true) %}

Are there any performance clue with my approach?

Thank you



98.9k

I don't think so, both solutions work



20.4k

Thanks for the incredible, for free, work you made and for the support you provide!