Search code examples
phpcodeignitercodeigniter-3

How can I use assets placed in the views directory in Codeigniter 3?


I am working on a online newspaper/blogging application with CodeIgniter 3.1.8 and Bootstrap 4. I have decided to add themes to it. The application is not HMVC, only MVC.

I thought it was a good idea to use the Twig template engine to the theme(s). For this purpose, I use CodeIgniter Simple and Secure Twig.

I want the views and assets corresponding to each theme to be placed in the same directory, with the theme's name.

I am trying to load the theme's assets from the views directory, like, for instance: application/views/themes/mytheme/assets/css/main.css.

In the post controller I have added the line $this->twig->addGlobal('maincss', base_url('application/views/themes/mytheme/assets/css/main.css'));

public function index() {

    //call initialization method
    $config = $this->_initPagination("/", $this->Posts_model->get_num_rows());

    $data = $this->Static_model->get_static_data();
    $data['pages'] = $this->Pages_model->get_pages();
    $data['categories'] = $this->Categories_model->get_categories();  

    //use limit and offset returned by _initPaginator method
    $data['posts'] = $this->Posts_model->get_posts($config['limit'], $config['offset']);

    $this->twig->addGlobal('siteTitle', 'My Awesome Site');
    //CSS, JS and other resources add to twig here, because PHP and Codeigniter functions are not available from Twig templates
    $this->twig->addGlobal('maincss', base_url('application/views/themes/mytheme/assets/css/main.css'));

    $this->twig->display('themes/mytheme/layout', $data);
}

In layout.twig I have:

<link rel="stylesheet" href="{{maincss}}">

Instead of the desired result, I get a 403 Forbidden page. To fix this issue, I added application/views/themes to .htaccess:

RewriteEngine on
RewriteCond $1 !^(index\.php|assets|application/views/themes/|images|js|css|uploads|favicon.png)
RewriteCond %(REQUEST_FILENAME) !-f
RewriteCond %(REQUEST_FILENAME) !-d
RewriteRule ^(.*)$ ./index.php/$1 [L]

The above solution fails for a reason I can not figure out.

What am I doing wrong?


Solution

  • Create a folder and name it assets outside application and then link it by using base_url like this:

    <link rel="stylesheet" href="<?php echo base_url('assets/back/css/bootstrap.min.css"')?>">