Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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') }}


7.4k
Accepted
answer

You can use it in volt like

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


2.2k

Tnx. I use

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

and fixed!