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!