We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Use my own Helpers in Volt

Hi Does anyone know How can I define my own View Helper and use it in my template ?

I define a helper class like this:

<?php

namespace MyApp\Helpers;

class dateHelper extends \Phalcon\Tag
{
    public static function convertDate($param)
    {
        return "TEST";
    }
}

and I use it in my service:

<?php

use MyApp\Helpers\dateHelper as dateHelper;

$di->set('dateHelper', function() {
    return new dateHelper();
});

$di->set('view', function() use ($config) {
    $view = new View();
    $view->setViewsDir($config->application->viewsDir);
    $view->registerEngines(array(
        '.volt' => function ($view, $di) use ($config) {
            $volt = new VoltEngine($view, $di);
            $volt->setOptions(array(
                'compiledPath' => $config->application->cacheDir . 'volt/',
                'compiledSeparator' => '_'
            ));

            $compiler = $volt->getCompiler();

            $compiler->addFunction(
                'convertDate',
                function ($resolvedArgs, $exprArgs) 
                {
                    return 'dateHelper::convertDate(' . $resolvedArgs . ')';
                }
            );

            return $volt;
        }
    ));
    return $view;
}, true);

but I can't use it in my volt template:

{{ convertDate('something') }}


10.5k
Accepted
answer

You can use it in volt like

 {{ tag.convertDate("something") }}


3.2k

Tnx. I use

{{ dateHelper.convertDate("something") }}

and fixed!