如何为资产(CSS, JS等)定义单独的URL,如base_url();在Codeigniter


How to define separate URL for assets (CSS, JS, Etc. ) like base_url(); in Codeigniter?

我得到了这个问题的几个答案,如在constant.php中定义它等

然而,它不能满足我,我猜其他Codeigniter开发人员也有同样的感觉。

谁能帮我一下,我又在重复我的问题,

如何定义另一个与base_url()相同的函数;在Codeigniter中,这样我就可以使用它为我的资产文件(CSS, JS等)

我喜欢这样处理资产。

我在application/helpers/

中创建了一个名为assets_helper的帮助器
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('css'))
{
    function css($nom)
    {
        return '<link rel="stylesheet" href="' . base_url() . 'assets/css/' . $nom . '.css " type="text/css" media="screen" />';
    }
}
if ( ! function_exists('css_print'))
{
    function css_print($nom)
    {
        return '<link rel="stylesheet" href="' . base_url() . 'assets/css/' . $nom . '.css " type="text/css" media="print" />';
    }
}
//This is only the part that handle css for the example
以下是我使用的完整帮助器:http://pastebin.com/ujETEXJ4

之后,在与index.php相同的级别创建这些文件夹:

|-Application
|-System
|-index.php
|-Assets
    |- css
    |- sass
    |- images
    |- js

把你需要的所有css文件放到新的css文件夹中。/js中的js也是一样,etc

在我的application/config/autolload .php中添加了我的新助手

$autoload['helper'] = array('assets', ...);

最后,在我的页眉:

<?php echo css('mycss'); ?> //I did not forgot the extension, it's how it works :)

最后给出:

<link rel="stylesheet" type="text/css" href="http://www.example.com/assets/css/mycss.css" />

这样我可以很容易地加载任何资源在我的代码:

css('mycss'); //load css
css_print('mycss'); //css media="print"
js('myjs'); //load js
img('myimg.png') //img tag
img_url('myimg.png') //path to an image

要使其工作,请确保在application/config.php

中正确设置了base_url
$config['base_url'] = "http://localhost/myawesomesite/";
//No index.php, don't forget the trailing slash!

不要忘记在application/config/autolload .php中加载url帮助器

$autoload['helper'] = array('url', 'assets');