2012-12-28 22 views

回答

14

伏功能作为字符串替换和不实际调用底层函数。 Volt将函数转换为相应的字符串,然后由PHP解释。

假设你有一个Locale类具有translate方法,例如:

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

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

    return $return; 
} 

此方法使用$_phrases内部数组来发现你传递和返回你想要的词组的文本相关的关键。如果未找到,则返回空字符串。

现在我们需要在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函数。它返回一个字符串\My\Locale::translate({$key})与传递的$key参数。这个Volt语法将被转换为PHP指令并由PHP执行。因此,视图的字符串:

<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> 
相关问题