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

How to dynamically load css file for each action in a controller?

我有一个名为 'Student' 的控制器,其中包含两个名为 'index' 和 'add' 的操作。 我想为每个动作加载不同的 css 文件。到目前为止,我尝试过的是,我已经导入了 Html Helper,创建了它的对象并调用了它的 css 方法。当我 运行 它时,它不会抛出任何错误,也不会显示预期结果。意思是,它没有在我的视图中动态加载 css 文件。我如何从控制器在不同的视图中动态加载 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");

    }

}

您可以在查看文件中执行此操作,例如

//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');

我是这样工作的,

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

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

并从布局文件访问这个 mycss 变量:-

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

成功了。

您还可以在“视图”>“元素”中创建一个全局布局文件,例如 default_assets.ctp

之后将此文件添加到您的默认布局文件中,例如,default_layout.ctp 在视图 > 布局文件夹中

然后在您的控制器中访问它之后

public function index(){
 $this->layout = "default_layout";
}