codeigniter – What is the best way to call files?

Question:

Well, I use codeigniter (but not specifically on it, any one that is MVC). I wanted to know how best to call my files, css, js, fonts, etc. I think the best way is to call it in the controller method, but let's suppose that for each page (method) I want to use a certain plugin Js code but not in the other one, how would I do it?

One day I did some conditionals (php), checking if the URI (controller name) is such load that file (css, js, etc), and that in the footer.php of my template. In case this would be the best alternative?

Thanks!

Answer:

Your basic idea of ​​conditioning by controller name is correct (in my opinion), but execution could be improved. Use file_helper.php to help accomplish the task. It's relatively simple: extend the helper as indicated in the documentation :

Create MY_file_helper.php in application/helpers/ and put the following in there:

if(!function_exists('js_loader')){

/**
* Carrega os scripts por demanda, a depender do controller ativo e do 
* diretorio definido
* @return string
*/
function js_loader() {
    //Captura a instancia do CI
    $ci = & get_instance();
    //Captura o controller ativo
    $controller = $ci->router->fetch_class();
    //Declara o diretorio onde estao os scripts do $controller. 
    //Este diretorio precisa estar acessivel ao navegador
    $jsdir = "assets/js/$controller/";
    //Checagem do $jsdir
    if(file_exists($jsdir)){
        $DirectoryIterator = new DirectoryIterator($jsdir);
        echo "<!--Scripts do controller $controller-->\n";
        foreach ($DirectoryIterator as $entry) {
            //Carrega apenas arquivos (exclui diretorios...)
            if ($entry->isFile()) {
                //Carrega apenas arquivos '.js'
                if (in_array($entry->getExtension(), ['js'])) {
                    $file = base_url($jsdir.$entry->getFilename());
                    echo "<script src='$file' charset='UTF-8'></script>\n";
                }
            }
        }
    }
   }
}

Load the helper into the CodeIgniter instance (or use autoload ) and call the function anywhere in the view :

<?php $this->load->helper('file'); ?>
 <html>
  <body>
   <?= js_loader() ?>
  </body>
</html>

Basically: all .js scripts that are inside "assets/js/$controller/" will be loaded when $controller is active.

Scroll to Top
AllEscort