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

Viewed 26048

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 *

5 Answers

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"/>

Try this

$config['base_url'] = "http://ur_site_url.com/";

Than in your view

<?php echo base_url('assets/css/style.css'); ?>

You can also use the html helper and add the stylesheet with link_tag depending on your setup and if you hide the public folder in your url, you must add public to the url.

<?php echo link_tag('public/css/style.css'); ?>

GOTO config/App.php and change this variable

public $baseURL = 'http://yoursite';

then you can access it as

<?php echo base_url();?>

Did you add base_url in the application/config/config.php file? Here: http://prntscr.com/pji8a5

Site URL is not defined which you give.

You have given http://localhost:8080/css.....

But It should http://localhost:8080/SITE_URL/css.....

If you add $config['base_url'] = "http://site_url.com/"; then you can give direct base_url('assets/css/style.css');

<link rel="stylesheet" href="<?php echo base_url('assets/css/style.css'); ?>">
<script src="<?php echo base_url('assets/js/js.css'); ?>"></script>

Thanks

Related