开发者

Push Array to $data variable to be passed to views

I'm using CI, and for every main page (for example contents) I load a specific css file in the constructor using :

$this->load->vars(array('add_css'=>array('contents')));

In my views, I check if the add_css array exists or not, if yes, I load the contents.css. Now in my controller file (in this case contents.php), I have lots of methods, and while all of them will always load the additional contents.css , specific methods will have (if any) their own add_css too, for example when I'm开发者_运维知识库 on method review, I want to load additional rating.css. What I did was :

$data['add_css'] = array('rating');

But it doesn't work because the rating.css overwrites the vars in the constructor.

So is there any way I can push the array? I've tried array_push($data['add_css'],'rating') but it doesn't work.

Thanks


The most elegant way I can think off would be this:
1. In your controller or if you have MY_Controller(it's much better) add new protected (so it is available from all controllers) property that will keep all loaded css files.

protected $_addCss = array();

2. Add new method for setting new css files to this array:

protected function _addCssFile($file)
{
    $this->_addCss[] = $file;
    return $this; //So you can chain it when adding but not necessary
}

3. New method for manual loading of all added css files.

protected function _loadCssFiles()
{
        //Load the vars then reset the property to empty array again
    $this->load->vars(array('add_css' => $this->_addCss));
    $this->_addCss = array();
    return $this;
}

4. In your application controller you can use it like this:

public function __construct()
{
        parent::__construct();
        $this->_addCssFile('contents');
}

public function test()
{
        //Chain the methods so you can add additional css files
    $this->_addCssFile('contents')
        ->_addCssFile('rating')
        ->_loadCssFiles()
        ->load->view('test');
}

5. In your view:

echo '<pre>';
print_r($add_css);
echo '</pre>';
Result:
Array
(
    [0] => contents
    [1] => contents
    [2] => rating
)


I had a similar problem. Read what's in the array, write to another array, push new info to it, overwrite the second array to data.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜