douye2572 2015-10-02 18:24
浏览 56
已采纳

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

I got several answers of this question, like Define it in constant.php Etc.

However, It doesn't satisfy me and I guess other Codeigniter developers felt the same.

Can anyone help me out, I am repeating my question again,

How can we define another function which works same like base_url(); in Codeigniter, so that i can use it for my assets file (CSS, JS, Etc.)

  • 写回答

1条回答 默认 最新

  • duanmei4362 2015-10-02 19:41
    关注

    Here is how I like to deal with assets.

    I create an helper called assets_helper in application/helpers/

    <?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
    

    Here is the full helper I use : http://pastebin.com/ujETEXJ4

    After that, at the same level as index.php I create those folder :

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

    Put all the css file you need in your new css folder. Same for js in /js, etc

    In my application/config/autoload.php I add my new helper

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

    Finally, in the header of my page(s) :

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

    Which will give at the end :

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

    This way i can easly load any ressource in my code :

    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
    

    ALSO:

    To make it work, make sure you have correctly set your base_url in application/config.php

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

    Don't forget also to load the url helper in application/config/autoload.php

    $autoload['helper'] = array('url', 'assets');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?