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.

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看