Wordpressor
Wordpressor

Reputation: 7543

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.

Upvotes: 2

Views: 1956

Answers (2)

Boris Delev
Boris Delev

Reputation: 424

...there is another way :) Volt has implemented php sprintf function with name format. So, you can do something like this:

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

The int of "foo" is: {{ "%d"|format(foo) }}

Good luck!

Upvotes: 2

Nikolay Mihaylov
Nikolay Mihaylov

Reputation: 3884

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 :)

Upvotes: 2

Related Questions