代码之家  ›  专栏  ›  技术社区  ›  GreyRoofPigeon

cakephp在视图函数中使用$this

  •  1
  • GreyRoofPigeon  · 技术社区  · 7 年前

    在我的Cakephp3.6项目中,我使用 TreeHelper 创建我的菜单。

    在我看来( 页数/索引.ctp )我使用:

    <?=$this->Tree->generate($pages,['alias'=>'title']); ?>
    

    它创建了一个基本的无序列表。

    使用TreeHelper,我可以使用回调函数更改列表项中的值:

    <?
    $this->Tree->generate($pages,['alias'=>'title','callback'=>'myFunction']);
    function myFunction($obj) {
        $id = $obj['data']['id'];
    
        $return = $this->Html->link('Edit',['action' => 'edit', $id]);
        $return .= $obj['data']['title'];
    
        return $return;
    }
    ?>
    

    我想使用HTMLHelper(即 $this->Html->link )创建链接,但它给出了以下错误:

    不在对象上下文中使用$this

    是否有解决方案/解决方案,以便在函数内部使用htmlhelper?

    1 回复  |  直到 7 年前
        1
  •  3
  •   ADmad    7 年前

    使用匿名函数代替全局函数。

    $this->Tree->generate($pages, [
        'alias' => 'title',
        'callback' => function ($obj) {
            $id = $obj['data']['id'];
    
            $return = $this->Html->link('Edit',['action' => 'edit', $id]);
            $return .= $obj['data']['title'];
    
            return $return;
        }
    ]);