3

我有一个团队数组,并且希望该团队名称在每个地方都显示团队名称。可以构建一个可以返回团队名称的全局函数,我从我的视图中调用该函数意味着 ctp 文件。

4

4 回答 4

6
please try this for west:

<?php
// controller name like app,users
// action name like getdata should be in controller
// and you can send parameter also
$output = $this->requestAction('controllerName/actionName/'.$parameter);
?>
于 2012-10-23T12:02:59.057 回答
3

对此有多种方法。我无法从您的描述中看出正是您正在寻找的东西。如果只是创建一个可在您的视图中访问的项目数组,我会将其放在 app_controller.php

var $teams = array('team1', 'team2', 'team3');

beforeFilter() {
   $this->set('teams', $this->teams);
}

然后在您的视图中,您可以通过变量访问数组:$teams

如果您只想在某些视图上调用团队,则为 EVERYTHING 设置此变量可能不是一个好主意。您可以通过在应用程序控制器中设置一个功能来解决它​​。

function get_teams_array() {
   $teams = array('team1', 'team2', 'team3');
   return $teams;
}

然后将调用此函数的元素放在一起:views/elements/team.ctp

<?php
$teams = $this->requestAction(
             array('controller' => 'app', 'action' => 'teams'),
             array('return')
          );

/** process team array here as if it were in the view **/
?>

然后你可以从你的视图中调用元素:

<?php echo $this->element('team'); ?>
于 2010-08-10T19:01:56.163 回答
0

您可以在 /app/config/bootstrap.php 文件中添加如下内容:

Configure::write('teams', array('team1', 'team2'));

然后在任何地方你都可以得到这个数组:

$teams = Configure::read('teams');

并使用它。

于 2010-08-10T11:27:32.737 回答
0

在 CakePHP 3.* 中,您可以使用 Helpers。

https://book.cakephp.org/3.0/en/views/helpers.html#creating-helpers

1 - 在src/View/Helper中创建你的助手:

/* src/View/Helper/TeamHelper.php */
namespace App\View\Helper;

use Cake\View\Helper;

class TeamHelper extends Helper
{
    public function getName($id)
    {
        // Logic to return the name of them based on $id
    }
}

2 - 一旦你创建了你的助手,你可以在你的视图中加载它。在/src/View/AppView.php
中添加调用:$this->loadHelper('Team');

/* src/View/AppView.php */
class AppView extends View
{
    public function initialize()
    {
        parent::initialize();
        $this->loadHelper('Team');
    }
}

3 - 一旦你的助手被加载,你可以在你的视图中使用它:

<?= $this->Team->getName($id) ?>
于 2018-05-04T01:08:56.223 回答