如何在CakePHP模型中设置变量并在视图中访问它



我有多个模型要将变量$section添加到其中,然后在sidenav.ctp中使用该值来动态更改侧边栏。例如,我的模型是:

class Resource extends AppModel {
    public $section = 'section1';
    public $displayField = 'name';
    public $order = 'modified DESC';
    //validation, relationships, etc.
}

然后我有另一个模型,比如:

class Topic extends AppModel {
    public $section = 'section2';
    public $tablePrefix = '';
    //validation, relationships, etc.
}

所以在sidenav.ctp中,我想做一些类似的事情:

<?php if ($this->section == 'section1') { ?>
    <li><?php echo $this->Html->link(__('Resources'), array('controller' => 'resources', 'action' => 'index')); ?></li>
    <li><?php echo $this->Html->link(__('Topics'), array('controller' => 'topics', 'action' => 'index')); ?> </li>
    <li><?php echo $this->Html->link(__('Log Out'), array('controller' => 'users', 'action' => 'logout')); ?> </li>
<?php } ?>
<?php if ($this->section == 'section2') { ?>
    <li><?php echo $this->Html->link(__('Resources1'), array('controller' => 'resources', 'action' => 'index')); ?></li>
    <li><?php echo $this->Html->link(__('Topics1'), array('controller' => 'topics', 'action' => 'index')); ?> </li>
    <li><?php echo $this->Html->link(__('Log Out1'), array('controller' => 'users', 'action' => 'logout')); ?> </li>
<?php } ?>

但是以这种方式访问CCD_ 4不起作用。我不知道如何在模型中设置值,然后在视图中访问它。我知道我可以在Controller中设置值,然后只通过$section访问它,但这需要我把它放在每个函数中。

在视图文件$this->name == 'ModelName' 中尝试

像这个例子:

<li <?php if($this->name == 'Users'){?> class="active" <?php } ?> >
            <a href="<?php echo $this -> Html -> url(array('plugin' => false, 'controller' => 'pages', 'action' => 'dashboard')); ?>">
                <i class="fa fa-dashboard"></i>
                <span><?php echo __('Dashboard', true); ?></span>
                <span class="label label-warning pull-right">1</span>
            </a>
        </li>

在控制器中beforeFilter或beforeRender方法:

//access variable from  model
$this->set('sections',$this->User->section);
//or set direct     
$this->set('sections','section1');

View的/Elements可以由任何控制器调用和渲染,因此它们不会自动知道您希望它引用什么数据,除非您将其从模型传递到视图。你能做的最接近的没有任何用处的事情是回显路由器模型方法,但结果取决于你所在的url。

您可以保存定义全局变量

Configure::write('my_var','this is model variable');

访问视图文件中的该变量,如

echo Configure::read('my_var'); 

最新更新