How can I load css or js file in codeigniter 4?

YJM picture YJM · Oct 15, 2019 · Viewed 11.9k times · Source

When I am trying to load css or javascript file then it returns 404 error.

I've tried to use helpers such as HTML helper's link_tag, URL helper's base_url methods, it will make a route to the file, but not loadable.

This is my Controller:

class Pages extends Controller{

    public function viewPage($page)
    {
        if(!is_file(APPPATH."/views/pages/$page.php")){
            throw new \CodeIgniter\Exceptions\PageNotFoundException($page);
        }

        helper('html');

        $data['title'] = $page == 'noticeboard' ? "page1" : "page2";

        if($page != "index"){
            echo view('templates/header', $data);
        }

        echo view("pages/$page", $data);

        if($page != "index"){
            echo view("templates/footer", $data);
        }
    }

}

My Router:

$routes->get("/", "Pages::viewPage/index");

Header in HTML:

<?=link_tag('public/css/style.css')?>

The assets folder is located in the very root of htdocs(I'm using xampp apache server).

And when I try to load CSS or JS, I get this error:

error message

I'm completely new to CodeIgniter, so any bits of help would be appreciated.

  • Directory structure:
htdocs
  -public
    --CSS
     ---style.css
    --JS
     ---app.js
  -app
    --controllers
      ---Page.php
    --views
      ---pages
        ----index.php

* I've changed my CSS, JS file routes from assets to public *

Answer

bhuvnesh pattnaik picture bhuvnesh pattnaik · Oct 15, 2019

As app is sibling folder of public folder,

And as per codeIgniter 4 .

anything you put in public folder can be accessed directly.

so it should be something like below to get css applied to the view.

In views folder lets say there's a file as index.php

then code should be like below:

index.php

    <link rel="shortcut icon" type="image/png" href="/css/style.css"/>