我在CodeIgniter应用程序中使用了大量的CSS和JavaScript。
这是我的样本控制器。
public function index() {
$this->load->view('site/title');
$this->load->view('site/menu');
$this->load->view('site/asset');
$this->load->view('site/css');
$this->load->view('site/js');
$this->load->view('site/content');
}
虽然我在视图中加载CSS文件和JavaScript文件,如下所示:
<link href="<?php echo base_url()?>css/all.css" rel="stylesheet">
<link href="<?php echo base_url()?>css/theme.css" rel="stylesheet">
我想要的是如果我将CSS文件夹位置更改为其他名称,(asset/css)
我需要更改所有功能中的路径。我怎样才能避免这种情况并简化它?
答案 0 :(得分:0)
您可以将资源放入数组中,然后执行foreach
循环:
<?php
$assets = array ( 'all.css', 'theme.css', ... );
foreach($assets as $asset) {
echo "<link href=\"<?php echo base_url()?>css/" . $asset . "\" rel=\"stylesheet\">" . "\n";
}
?>
输出:
<link href="<?php echo base_url()?>css/all.css" rel="stylesheet">
<link href="<?php echo base_url()?>css/theme.css" rel="stylesheet">
答案 1 :(得分:0)
您可以创建一个库来管理app/libraries
中的资产
class Assets{
/** url to assets dir */
protected $urlToAssets
/** @var array */
protected $cssFiles;
public function __construct()
{
$this->urlToAssets = base_url('assets/');
$this->cssFiles = array();
}
function addCss($name)
{
$this->cssFiles[] = $name
}
function printCssFiles()
{
foreach ($this->cssFiles as $css)
{
echo '<link href="' . $this->urlToAssets . $css . '" rel="stylesheet">';
}
}
}
然后,在ypur控制器中你可以这样做:
$this->load->library('assets');
$this->assets->addCss('cool.css');
$this->assets->addCss('cool.plugin.css');
最后,在视图中渲染资源:
$this->assets->printCssFiles();
然后,您可以改进库:
class Assets{
/** url to assets dir */
protected $urlToAssets
/** @var array */
protected $cssFiles;
/** @var array */
protected $jsFiles;
public function __construct()
{
$this->urlToAssets = base_url('assets/');
$this->cssFiles = array();
$this->jsFiles = array();
}
function addCss($name)
{
$this->cssFiles[] = $name
}
function addJs($name, $section = 'header')
{
$this->jsFiles[$section] = $name
}
function printCssFiles()
{
foreach ($this->cssFiles as $css)
{
echo '<link href="' . $this->urlToAssets . $css . '" rel="stylesheet">';
}
}
function printJsFiles($section)
{
foreach ($this->jsFiles as $js)
{
echo '<script src="' . $this->urlToAssets . $js . '"></script>';
}
}
}
现在,您可以在控制器中执行以下操作:
$this->load->library('assets');
$this->assets->addJs('jquery.js', 'header');
$this->assets->addJs('jquery.plugin.js', 'footer');
在标题视图中,您可以调用相应的js文件:
$this->assets->printJsFiles('header');
或者在页脚中:
$this->assets->printJsFiles('footer');
答案 2 :(得分:0)
你可以通过创建一个公共加载器来实现,默认情况下加载 css,js和menu ,然后根据需要动态加载主要内容。
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class site extends CI_Controller
{
//public loader here
public function loader($common)
{
$this->load->view($common);
$this->load->view('site/asset'); //which contains the css, js and menu folder
}
//index page here
public function index()
{
$this->loader('index');
}
//about page here
public function about()
{
$this->loader('about');
}
//blog page here
public function blog()
{
$this->loader('blog');
}
}