CakePHP 在视图函数中使用 $this
CakePHP use $this in view function
在我的 CakePHP3.6 项目中,我使用 TreeHelper 创建我的菜单。
在我看来(pages/index.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
)创建链接,但它给我这个错误:
Using $this when not in object context
是否有解决方案/解决方法,以便我可以在函数内部使用 HtmlHelper?
使用匿名函数代替全局函数。
$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;
}
]);
在我的 CakePHP3.6 项目中,我使用 TreeHelper 创建我的菜单。
在我看来(pages/index.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
)创建链接,但它给我这个错误:
Using $this when not in object context
是否有解决方案/解决方法,以便我可以在函数内部使用 HtmlHelper?
使用匿名函数代替全局函数。
$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;
}
]);