How can I set own Tag class in Volt (Phalcon)

3.1k Views Asked by At

I want to redeclare and add some methods to helper Tag.

class MyTags extends \Phalcon\Tag
{
    public static function mytag($params)
    {
       <...>
    }
}

in services.php

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

But it works only for PHP engine, not for Volt.

{{ mytag() }}

returned

Undefined function 'mytag'
1

There are 1 best solutions below

0
On BEST ANSWER

First of all: don't use tag as your service name because it's already used by Phalcon's Tag object. Secondly you can use static methods from class.

Below is a working example for myTag using config from my app with changed names for your example.

$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,
                        'compiledSeparator' => '_',
                        'compileAlways' => false
                    )
                );
                $compiler = $volt->getCompiler();

                // add a function
                $compiler->addFunction(
                    'myTag',
                    function ($resolvedArgs, $exprArgs) {
                        return 'MyTags::mytag(' . $resolvedArgs . ')';
                    }
                );

                // or filter
                $compiler->addFilter(
                    'myFilter',
                    function ($resolvedArgs, $exprArgs) {
                        return 'MyTags::mytag(' . $resolvedArgs . ')';
                    }
                );

                return $volt;
            }
        )
        );

        return $view;
    },
    true
);

Then you can use your myTag() function in volt views.

But if you want to use object then don't use static methods:

class MyTags extends \Phalcon\Tag
{
    /**
     * Look no static keyword here
     */
    public function mytag($params)
    {
       <...>
    }
}

in services use object:

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

and then in in volt:

{{ mahTag.mytag() }}