问题
I am using CodeIgniter Version 2.1 & trying to link assets like images,stylesheets, javascript files etc in my views by using, header.php
:
<link href="<?php base_url();?>css/style.css" rel="stylesheet" />
my controller code, calls the view:
<?php
class Main extends CI_Controller{
public function index() {
$this->load->view('header');
}
- The view file from which I am trying to load the asset is located
../application/views/header.php
. - the css file is loaded:
../application/views/css/style.css
this does not work. I get 404 - Page not found error.then, I tried moving css/style.css
outside ../application
directory in webroot. To my surpise, having assets in webroot(outsite ../application/views) seems to work nicely.
Now, My Question is
- Is having our assets directly in webroot, outsite
../application
directory right approach? If YES/NO, then why? - If having assets directly in webroot is a good idea, than should I move
../application/views
directory in webroot as well? How?
PS: I am new to CodeIgniter framework, so unaware of the best practices
回答1:
It is best to put your assets in the webroot folder. When requesting assest from the server (depending on your setup), it will start from the root directory and work it's way down.
http://yoursite.com/application/views/css/mystyles.css
if it's in the root you only need to go from there
http://yoursite.com/css/mystyles.css
Although it might be worth putting them all inside a folder (/assets) to keep them contained, as well as the ability to write a more effective rewrite rule (if you are trying to remove the index.php from the url) to ignore the single folder instead of all the individual folders (/css, /js, etc)
As for the views folder, it's best if you leave it in the application
folder as CodeIgniter has a built in loader that automatically checks /application/views
for the view file when you use the code $this->load->view('myview')
Although there are way to move the views folder, if you are new to CI it's probably best to leave it there for now.
回答2:
If you see this, the section where .htaccess
is used to remove index.php
from the urls, that has a rewrite condition:
RewriteCond $1 !^(index\.php|images|robots\.txt)
In this line, images is a folder that will be ignored while mod-rewriting. So, you can replace it by assets, put all your directly linking files there, and happily use them.
RewriteCond $1 !^(index\.php|assets|robots\.txt)
EDIT: my bad, hadn't seen the date the question was asked. nevertheless, should be useful for someone.
回答3:
For linking css you can do something like:
echo link_tag('css/mystyles.css');
Check this for ref: http://codeigniter.com/user_guide/helpers/html_helper.html
来源:https://stackoverflow.com/questions/8278149/how-to-link-assetsimages-stylesheet-etc-in-views-for-codeigniter-2-1