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 Custom Function not working?

I am using this to create a custom function 'file_exists'.

$volt->getCompiler()->addFunction('file_exists', function($file) {
        return file_exists('https://localhost/balloon/' . $file);
});

When I try to call the function in an if statement, the compiled template is blank (if statement).

{% if file_exists("public/images/edited/" ~ picture.position ~ "/" ~ session.get('username') ~ "_" ~ picture.text|url_encode ~ "." ~ picture.extension) %}
{% endif %}


98.9k
Accepted
answer

Actually, a Volt function must not execute code directly but it has to return "code" that is inserted as part of the generated code:

$volt->getCompiler()->addFunction('file_exists', function($resolvedArgs) {
    return "file_exists('https://localhost/balloon/'" . $resolvedArgs . ")";
});

https://docs.phalcon.io/en/latest/reference/volt.html#id1