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 关于#c语言#的问题:构成555单稳态触发器,采用LED指示灯延时时间,对延时时间进行测量并显示(如楼道声控延时灯)需要Proteus仿真图和C语言代码
  • ¥50 神舟笔记本,没有linux的驱动,装的Ubuntu系统,想把风扇速度调到最大
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,怎样解决呢?
  • ¥50 如何用单纯形法寻优不能精准找不到给定的参数,并联机构误差识别,给定误差有7个?matlab
  • ¥15 workstation加载centos进入emergency模式,查看日志报警如图,没有XFS,怎样解决呢?
  • ¥15 应用商店如何检测在架应用内容是否违规?
  • ¥15 Ubuntu系统配置PX4
  • ¥50 nw.js调用activex
  • ¥15 数据库获取信息反馈出错,直接查询了ref字段并且还使用了User文档的_id而不是自己的
  • ¥15 将安全信息用到以下对象时发生以下错误:c:dumpstack.log.tmp 另一个程序正在使用此文件,因此无法访问