dpxw17759 2014-08-10 03:12
浏览 17
已采纳

Phalconphp FW定制伏特函数并将变量插入函数中

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.

  • 写回答

1条回答 默认 最新

  • dongqiao1151 2014-08-10 10:54
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?