【问题标题】:Change admin layout in CakePHP在 CakePHP 中更改管理布局
【发布时间】:2018-11-05 20:46:46
【问题描述】:

我在 cakephp 工作,我的 /app/config/routes.php 文件中有以下两行:

/**
 * ...and setup admin routing
 */
 Router::connect('/admin/:controller/:action/*', array('action' => null, 'prefix' => 'admin', 'admin' => true, 'layout' => 'admin' ));
/**
 * ...and set the admin default page
 */
 Router::connect('/admin', array('controller' => 'profiles', 'action' => 'index', 'admin' => true, 'layout' => 'admin'));

我在 /app/views/layouts/admin.ctp 也有一个布局

但是,当我访问管理 URL 时,布局没有改变

【问题讨论】:

    标签: php cakephp


    【解决方案1】:

    创建一个app/app_controller.php 并将其放入:

    <?php
    class AppController extends Controller {
    
        function beforeFilter() {
            if (isset($this->params['prefix']) && $this->params['prefix'] == 'admin') {
                $this->layout = 'admin';
            } 
        }
    
    }
    

    如果您在其他控制器中使用parent::beforeFilter();,请不要忘记在您的控制器中调用它。

    半相关的问题,你不需要定义路由,你只需要启用Routing.admin 配置选项并在app/config/core.php 中将其设置为admin。 (CakePHP 1.2)

    【讨论】:

    • 谢谢!在 Routing.admin 配置选项上: 1. 已更改为 routing.prefix 2. 我更改它是因为它没有提供“布局”选项,但现在这无关紧要 3. 即使使用 Routing.admin(或前缀)on,我仍然需要索引页面的第二条路线
    • 仍然需要您的第二条路线,但是我不相信您需要'layout' => 'admin' 所做的只是在您的 url 上添加一个参数(如果您设置通过),这只会是在该页面上可用。 Routing.prefixes 的作用类似于您的第一条路线:)
    【解决方案2】:

    在 beforeFilter() 函数中添加此代码 app_controller.php

    <?php    
    
    class AppController extends Controller {
    
    function beforeFilter() {
        if (isset($this->params['prefix']) && $this->params['prefix'] == 'admin') {
            $this->layout = 'admin';
        } else {
           $this->layout = 'user';  
        } 
    
        }
    
    }
    ?>
    

    设置 layout='admin' in routes.php

    <?php    
    Router::connect('/admin', array('controller' => 'users', 'action' => 'index','add', 'admin' => true,'prefix' => 'admin','layout' => 'admin'));
    ?>
    

    【讨论】:

      【解决方案3】:

      对于 CakePHP 3.X,您应该编辑您的 src/View/AppView.php 文件并将以下代码添加到您的 initialize() 方法中:

      public function initialize()
      {
          if ($this->request->getParam('prefix') === 'admin') {
              $this->layout = 'Plugin.layout';
          }
      }
      

      【讨论】:

        【解决方案4】:

        上面的方法很好,但是如果您希望在登录时更改每个页面的布局,您可以使用 Auth Component 尝试以下操作

        function beforeFilter() {
            if ($this->Auth->user()) {
                $this->layout = 'admin';
            }
        }
        

        【讨论】:

          【解决方案5】:

          对于 cakephp 3.0,您可以通过在 AppController 的 beforeRender 中调用 Auth->user 来设置视图变量。这是我的 beforeRender:

          public function beforeRender(Event $event)
          {
              ///...other stuff
          
              $userRole = $this->Auth->user();
              $this->set('userRole', $userRole['role']);
          }
          

          【讨论】: