phpvariablesintphalconvolt

How to convert a variable to int in Phalcon's .volt?


I have this code in .volt (Phalcon):

{% set foo = myFunction(data, 'data_source', 0) %}

It returns non-negative numbers, the problem is when it's empty I'm getting "" instead of "0". How can I force volt to always return int as foo, so everything will work as expected but it won't throw empty variable errors?

I'd rather avoid using <?php ... ?>.

I've been looking through http://voltframework.com/docs with no luck.

Thank you.


Solution

  • There are two options you can choose from:

    1) Creating own volt function:

    $compiler->addFilter(
        'int',
        function ($resolvedArgs, $exprArgs) {
            return 'intval(' . $resolvedArgs . ')';
        }
    );
    

    More info here: https://docs.phalconphp.com/en/latest/reference/volt.html#id2

    2) Using built in filters from volt. In your case you can use DEFAULT fitler to set default value as 0 if no value is returned. Full list of built in functions here: https://docs.phalconphp.com/en/latest/reference/volt.html#filters

    And of course other options would be to modify your function to always return a value or use the PHP syntax inside volt, which is a bit ugly :)