如何为控制器中的每个操作动态加载css文件?

时间:2017-05-14 14:15:39

标签: php cakephp cakephp-2.6

我有一个名为'学生'有两个叫做' index'并且'添加'。 我想为每个操作加载不同的css文件。到目前为止,我已经尝试过,我已经导入了Html Helper,创建了它的对象并调用了它的css方法。当我运行它时,它不会抛出任何错误,也不会显示预期的结果。意思是,它不是在我的视图中动态加载css文件。如何从Controller中动态加载不同视图中的css文件?

代码: -

<?php

App::import('Helper','Html');

class StudentController extends AppController
{
    public function index()
    {
//        $current_controller = $this->params['controller'];
//        echo $current_controller;

        //$view=new  View(new Controller($current_controller));

        //$Html=new HtmlHelper($view);
        $Html=new HtmlHelper(new View(null));
        //$html=new HtmlHelper(new View());
        $Html->css('cake.generics');

        //echo ;
        //$this->Html->css("cake.generics");
    }

    public function add()
    {
//        $current_controller = $this->params['controller'];
//        echo $current_controller;

        $html=new HtmlHelper(new View(null));
        $html->css("mystyle.css");

    }

}

3 个答案:

答案 0 :(得分:1)

您可以在视图文件中执行此操作,例如

//in your View/Students/add.ctp
$this->Html->css('yourstyle', array('block' => 'yourStyle'));

//in your layout file
echo $this->fetch('yourStyle');

与js文件相同

// in your view
$this->Html->script('yourjs', array('block' => 'yourJs'));

//in your layout file
echo $this->fetch('yourJs');

答案 1 :(得分:1)

您还可以在View&gt;中创建全局布局文件。像default_assets.ctp

这样的元素

之后,在默认布局文件中添加此文件,例如在View&gt;中的default_layout.ctp。布局文件夹

并在您的控制器中访问后,如

actions: {
sendData: function () {
  this.set('showLoading', true);

  let data = {
    startTime: date.normalizeTimestamp(this.get('startTimestamp')),
    endTime: date.normalizeTimestamp(this.get('endTimestamp')),
    type: constants.ENTERPRISE.REPORTING_PAYMENT_TYPE
  };

  api.ajaxPost(`${api.buildV3EnterpriseUrl('reports')}`, data).then(response => {
    this.set('showLoading', false);

    console.log("Comes here!!!!");
    console.log(this.get('model'));
    this.get('model').toArray().addObject(Ember.Object.create(response));

    return response.report;
  }).catch(error => {
    this.set('showLoading', false);
    if (error.status === constants.HTTP_STATUS.GATEWAY_TIMEOUT) {
      this.notify.error(this.translate('reports.report_timedout'), this.translate('reports.report_timedout_desc'));
    } else {
      this.send('error', error);
    }
  });
}

答案 2 :(得分:0)

我以这种方式工作,

我在控制器中添加了“mycss”变量,索引操作: -

$this->set('mycss','custom');

从布局文件中访问此mycss变量: -

if(isset($mycss)){
    $this->Html->css("$mycss");
}

它有效。