Reputation: 8360
I am a newbie in codeigniter. I want to load jquery on every page. I know we have to use autoload.php. But inside it there is section where static contents like js or css can be included. How to do this? I created another index like this
$autoload['static'] = array(JS_LIBS_PATH.'/jq.js');
But obviously nothing happened. That constant has been defined in config,php. Using same constant I could put jq on a page, but what about autoload ?
Upvotes: 0
Views: 4049
Reputation: 8135
In CI, Helpers, as the name suggests, help you with tasks. So we can load jquery automatically as a helper.
Inside the jquery_helper.php file call the jquery-2.1.4.min.js file:
<script src="assets/js/jquery-2.1.4.min.js"></script>
Inside /var/www/html/ci3/application/config/autoload.php call the jquery_helper.php:
$autoload['helper'] = array('jquery');
Now the jquery will be load automatically and you can use it in all your views.
Upvotes: 0
Reputation: 102765
I can think of several elaborate solutions but I really think that javascript is presentation-level and shouldn't be in your autoload, models, controllers, etc.
You can just use a master view file of some kind with your <head>
and basic HTML requirements:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $title; ?></title>
<script src="/path/to/jquery.js"></script> <!-- jQuery on every page -->
<!-- alternatively, loop through files in a custom config setting -->
<?php foreach (config_item('default_js') as $src): ?>
<script src="<?php echo $src; ?>"></script
<?php endforeach; ?>
<!-- ... and/or loop through files set in a controller -->
<?php foreach ($js_files as $src): ?>
<script src="<?php echo $src; ?>"></script
<?php endforeach; ?>
</head>
<body>
<header />
<?php echo $content; ?>
<footer />
</body>
</html>
Then just load views like this:
$data['js_files'] = array('draggable.js', 'widgets.js');
$content = $this->load->view('index', $data, TRUE);
$this->load->view('master', array('title' => 'Home', 'content' => $content));
Of course this is just one solution out of millions, but the idea of Codeigniter "autoloading" CSS and Javascript makes no sense, you have to "load" it yourself in one way or another - how you do it is completely up to you.
Upvotes: 2
Reputation: 1973
Here's what I've done for a while that works quite well.
Your asset files (javascripts, stylesheets, etc) go in your asset folders /assets/js
, /assets/css
and so forth.
In your config file, you define a default array of JavaScript files to load.
$config['default_asset_js'] = array('js/jquery.js', 'js/jquery-ui.js');
In your views, you have a section that runs through that array and outputs each of them.
foreach($this->config-item('default_asset_js') as $file_name)
{
echo '<script src="' . base_url('assets/' . $file_name) . '"></script>';
}
You can probably also get creative and add to that array in your controller, if you have specific pages that require additional files to be loaded.
Upvotes: 1