Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set up a user defined function in Volt (Phalcon)

Tags:

php

phalcon

volt

How can I set up a user defined function in Volt? For instance I want to call a function that would translate strings in my views as such:

<div class='page-header'>
    <h2>{{ tr('session_login_title') }}</h2>
</div>

and I want the tr to map to a function \My\Locale::translate($key)

like image 273
Nikolaos Dimopoulos Avatar asked Dec 28 '12 15:12

Nikolaos Dimopoulos


1 Answers

Volt functions act as string replacements and do not actually call the underlying function. Volt translates the function into the relevant string which in return is interpreted by PHP.

Suppose you have a Locale class which has a translate method as such:

public static function translate()
{
    $return = '';

    if (isset(self::$_phrases[$key]))
    {
        $return = self::$_phrases[$key];
    }

    return $return;
}

This method uses the $_phrases internal array to find the relevant key that you pass and return the text of the phrase you want. If not found it returns an empty string.

Now we need to register the function in Volt.

    $di->set(
        'volt',
        function($view, $di) use($config)
        {
            $volt = new \Phalcon\Mvc\View\Engine\Volt($view, $di);
            $volt->setOptions(
                array(
                    'compiledPath'      => $config->app_volt->path,
                    'compiledExtension' => $config->app_volt->extension,
                    'compiledSeparator' => $config->app_volt->separator,
                    'stat'              => (bool) $config->app_volt->stat,
                )
            );
            $volt->getCompiler()->addFunction(
                'tr',
                function($key)
                {
                    return "\\My\\Locale::translate({$key})";
                }
            );

            return $volt;
        },
        true
    );

Note how the tr function is registered. It returns a string \My\Locale::translate({$key}) with the passed $key parameter. This Volt syntax will be translated to PHP directives and executed by PHP. Therefore the view string:

<div class='page-header'>
    <h2>{{ tr('session_login_title') }}</h2>
</div>

after Volt processes it becomes:

<div class='page-header'>
    <h2><?php echo \My\Locale::translate('session_login_title') ?></h2>
</div>
like image 123
Nikolaos Dimopoulos Avatar answered Oct 19 '22 13:10

Nikolaos Dimopoulos