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 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘