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 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵