如何在Volt(Phalcon)中设置用户定义的函数 [英] How can I set up a user defined function in Volt (Phalcon)

查看:171
本文介绍了如何在Volt(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>

,并且我希望tr映射到函数\My\Locale::translate($key)

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

推荐答案

Volt函数充当字符串替换,实际上并未调用基础函数. Volt将函数转换为相关的字符串,作为回报,PHP将对其进行解释.

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.

假设您有一个Locale类,该类具有这样的translate方法:

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;
}

此方法使用$_phrases内部数组查找您传递的相关键,并返回所需短语的文本.如果找不到,它将返回一个空字符串.

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.

现在我们需要在Volt中注册该功能.

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
    );

请注意如何注册tr功能.它返回带有传递的$key参数的字符串\My\Locale::translate({$key}).此Volt语法将转换为PHP指令并由PHP执行.因此,视图字符串:

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>

伏特处理后变为:

<div class='page-header'>
    <h2><?php echo \My\Locale::translate('session_login_title') ?></h2>
</div>

这篇关于如何在Volt(Phalcon)中设置用户定义的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆