Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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



12.1k
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



85.3k

You can use 'defined':

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


12.1k
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



85.3k

I don't think so, both solutions work



12.1k

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