简体   繁体   中英

phalconphp custom functions in volt doesn't work

I have a problem with accessing variables in my custom function.

My code is:

{{ myFunction(variableFromController) }}

And PHP:

$compiler->addFunction('myFunction',function($resolvedArgs,$exprArgs)use($di,$compiler){
   $arg = $compiler->expression($exprArgs[0]['expr']); $lang = $di->get('lang');
   echo $lang->translate($arg);
});

Problem is that compiler will return variable as string "$variableFromController". What I'm doing wrong?

Volt (or other engine) is just some kind of additional layer over PHP so any functions that you are adding to compiler are more like a shortcuts. They are not "doing" something by themselves. They are just printing part of code that will be excuted later.

In other words, this is bad:

$compiler->addFunction('myFunction',function($resolvedArgs,$exprArgs)use($di,$compiler){
   // do stuff with $value
   return $someClass->someMethod($value);
});

And this is good:

$compiler->addFunction('myFunction',function($resolvedArgs,$exprArgs)use($di,$compiler){
   $arg = $compiler->expression($exprArgs[0]['expr']); $lang = $di->get('lang');
   return '\\My\\Class::staticMethod('.$arg.', '.$lang.')';
});

Cheers!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM