这样组织CSS、JS等文件好不好
本帖最后由 phoenixg 于 2012-5-1 11:43 编辑看见群里有人讨论CSS、JS文件的组织问题,我之前是这么解决的(见下),想听听大家的建议。
目录结构:(使用了modules)
assets/
- css/
- global.css
- module_name1/
- controller1_view1.css
- controller1_view2.css
- js/
- jqueryplugins/
- img/
- icon/
application/
- library/Asset.php 自定义一个assets处理类(代码见下)
- modules/
- module_name1/
- controllers/
- views/
- controller1_view1.php (代码见下)
- controller2_view2.php
- views/
- wholesite/
- header.php (代码见下)
- footer.php (代码类似header.php)
<?phpif (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* 加载Asset的类
*
* 用于加载各自页面自己的css、js、icon等等
* 用于处理跟asset有关的操作
* @author
*
*/
class CI_Asset {
private $_CI;
private $_assets_url;
function __construct()
{
$this->_CI = & get_instance();
$this->_assets_url = $this->_CI->config->item('assets_url');
log_message('debug','CI Asset class loaded');
}
/**
* add asset
*
* eg. $this->asset->add_asset(basename(dirname(dirname(__FILE__))), 'controller_view', 'css')
*
* @param module name
* @param file name
* @param asset type
*/
public function add_asset($module_name, $file_name, $asset_type)
{
return $this->_assets_url . $asset_type . '/' . $module_name . '/' . $file_name . '.' . $asset_type;
}
}
<?php
$data['header_asset'] = array(
'css' => array(
$this->asset->add_asset(basename(dirname(dirname(__FILE__))), 'controller1_view1', 'css')
)
);
$this->load->view('wholesite/header', $data);
?>
<?php
$data['footer_asset'] = array(
'js' => array(
$this->asset->add_asset(basename(dirname(dirname(__FILE__))), 'controller1_view1', 'js'),
)
);
$this->load->view('wholesite/footer', $data);
?>
<html>
<head>
<title><?php echo isset($title)? $title : '';?></title>
<!-- 加载全部页面都需要的CSS、JS等 -->
<link rel="stylesheet" href="<?php echo $this->config->item('assets_url');?>css/global.css" type="text/css">
<link rel="stylesheet" href="<?php echo $this->config->item('assets_url');?>jqueryplugins/jbreadcrumb/Styles/BreadCrumb.css" type="text/css">
<!-- header 加载页面专属的CSS、JS等 -->
<?php if (isset($header_asset) && is_array($header_asset)):?>
<?php foreach ($header_asset as $type => $addrs):?>
<?php if($type == 'css'):?>
<?php foreach ($addrs as $addr):?>
<link rel="stylesheet" href="<?php echo $addr;?>" type="text/css">
<?php endforeach;?>
<?php elseif($type == 'js'):?>
<?php foreach ($addrs as $addr):?>
<script type="text/javascript" src="<?php echo $addr;?>"></script>
<?php endforeach;?>
<?php endif; ?>
<?php endforeach;?>
<?php endif;?>
</head>
我觉得这样很不错。
我基本上也是这么弄的。 有两处我还不满意:
- 视图里循环加载css和js,由于区分了header加载和在footer加载,所以要在header.php和footer.php里分别写两遍几乎一样的循环遍历代码
- asset扩展类的add_asset方法有没有更好的改进方法,我觉得给的参数太多
页:
[1]