问题
I have created a custom function I can access from the volt. The function seems to work fine, but I cannot manage to send the variable to the function. It sends the variable as text instead of its value.
The twig function:
$volt->getCompiler()->addFunction('getusergroup', function ($user) {
return \Models\User::getUserGroup($user);
});
The function in the Model:
public static function getUserGroup($user) {
return UserGroup::find(array('conditions' => 'user_id = ' . $user));
}
The lines in Twig to call the function:
{% for member in getusergroup(staff.id) %}
{{ member.Group.name }}
{% endfor %}
The error I get:
'Scanning error before 'staff->id' when parsing: SELECT [Models\UserGroup].* FROM [Models\UserGroup] WHERE user_id = $staff->id (78)' (length=131)
As you can see, in stead of $staff->id
being an integer, it's the text.
How do I go about sending the actual ID to the function?
By the way, I am using twig in combination with Phalcon and followed the instructions in this article: http://phalcontip.com/discussion/60/extending-volt-functions
回答1:
If you dump $user
inside of your method public static function getUserGroup($user)
, you will receive this $staff->id, but you actually want something like 42.
To avoid this register the Volt function like this:
$volt->getCompiler()->addFunction('getusergroup', function ($resolvedArgs, $exprArgs) {
return 'Models\User::getUserGroup(' . $resolvedArgs . ')';
});
More info on Extending Volt Functions
来源:https://stackoverflow.com/questions/38880434/sending-variable-from-volt-to-custom-function