简体   繁体   中英

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.

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

...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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM