我有一个在 cakephp 2 中开发的站点,我希望在我的 default.ctp 中有一个菜单,其中包含从数据库中获取的一些元素。如何更改我必须使用的控制器的元素?我必须把我的查询放在哪里?因为如果我进一个model很容易但是进default.ctp?我怎样才能做到这一点?这是我的 default.ctp:
<body>
<div class="content">
<div id="navigation">
<ul>
<?php
if (!empty($authUser)) {
?>
<li><?php echo $this->Html->link('I want to change this', array('controller' => 'ingredients', 'action' => 'index')); ?></li>
<li><?php echo $this->Html->link('I want to change this', array('controller' => 'brands', 'action' => 'index')); ?></li>
<li><?php echo $this->Html->link('I want to change this', array('controller' => 'manufacturers', 'action' => 'index')); ?></li>
<?php
// $is_logged from UsersController->beforeFilter
echo $this->element ('header_menu_logged');
} else {
?>
<li><?php echo $this->Html->link('Competizioni', array('controller' => 'brands', 'action' => 'index')); ?></li>
<li><?php echo $this->Html->link('Cerca', array('controller' => 'manufacturers', 'action' => 'index')); ?></li>
<?php
// $current_model
echo $this->element ('header_menu', array('selected' => 'Pippo'));
}
?>
</ul>
</div>
<div class="page">
<?php
// messaggi di stato per le azioni
if (empty($flash_element)) {
$flash_element = $this->Session->read('flash_element');
if (empty($flash_element)) {
$flash_element = 'default';
}
}
// echo '>'.$flash_element.'<';
$auth_msg = $this->Session->flash('auth', array ('element' => 'flash_'.$flash_element));
$flash_msg = $this->Session->flash('flash', array ('element' => 'flash_'.$flash_element));
if (!empty($auth_msg)) {
echo $auth_msg;
}
if (!empty($flash_msg)) {
echo $flash_msg;
}
?>
<section><!--class="contents"-->
<?php echo $content_for_layout; ?>
</section>
</div>
</div>
</body>
Run Code Online (Sandbox Code Playgroud)
好吧,我建议$this->set('anyString', $varStringOfTheLink);在您的beforeRender()或beforeFilter()在 appController.php 中进行。
从那里进行查询,然后使用该set()函数为您的视图设置一个变量。
然后在 default.ctp 中,您将能够使用$anyString.
所以做一个快速总结。在您的 appController 中,在过滤器之前或渲染之前执行查询,然后设置它以便您的视图可以使用它。该set()函数的第一个参数是您要在视图中使用的 var 的名称。$之前放一个。第二个参数是你想要的变量的值。
//appController.php
function beforeFilter(){
$myQueryVar = $this->Model->find('whateverIWant');
$this->set('myLinkOne', $myQueryVar);
}
//layouts/default.ctp
echo $this->Html->link($myLinkOne, array('controller' => 'ingredients', 'action' => 'index'));
Run Code Online (Sandbox Code Playgroud)