I have a problem with inserting dynamic variables into custom volt functions.
For example i have a code:
{{ myFunction(variableFromController) }}
And accessing the variable:
$compiler->addFunction('myFunction',function($resolvedArgs,$exprArgs)use($di,$compiler){
$arg = $compiler->expression($exprArgs[0]['expr']);
$lang = $di->get('lang');
echo $lang->translate($arg);
});
So problem is that compiler returns a variable as string "$variableFromController", so i cannot acccess content from variable.
Do you know how to pass variable correct into custom function or is a problem in accessing ?
Thanks.
I think that there is a misconception of what Volt's function is. It looks like it is. Your Volt function should return a string which can be then evaluated by PHP. As an example from Phalcon's docs:
$compiler->addFunction('widget', function($resolvedArgs, $exprArgs) {
return 'MyLibrary\Widgets::get(' . $resolvedArgs . ')';
});
So based on that I think that your function should return (but I haven't tested this):
$compiler->addFunction('myFunction',function($resolvedArgs,$exprArgs)use($di,$compiler){
$arg = $compiler->expression($exprArgs[0]['expr']);
return '$this->lang->translate(' . $arg . ');';
});
This is because Volt acts as a compiler of Volt (Twig) syntax to PHP templates (you can check this by examine volt's output folder. So it output PHP files that are later used to render views.
I've found that adding helper object to di container is better for complex operations. I can add a helper to di container end us it as below:
Provided the code from above you could skip all the myFunction
thing and just use lang
from di
container:
{{ lang.translate(variable) }}
since you can directly access all services from di in view.