Welcome Guest, Not a member yet? Register   Sign In
How to use CI classes in css and js files
#1

[eluser]mjijackson[/eluser]
Is is possible to use the CI classes in javascript and css files? I'd specifically like to use the URL helper in these files so that I can set the base url for Ajax calls and background image urls.

For now, I've created a new folder called 'assets' and placed it in the root of my site directory. All of my js and css files are in that directory.
#2

[eluser]Michael Wales[/eluser]
Not really. There is a round-about way of going about it but it's going to make your source code look sloppy to an outsider.

You could place your "pre-parsed" javascript and css files in the Views folder as .php files (or make a new function [which is what I would do] $this->load->css() and $this->load->js().

Then, load those 2 files just as you would a normal view - when loading them into a variable:
Code:
$data['style'] = $this->load->css('style', , TRUE);
$data['script'] = $this->load->js('rollover', , TRUE);

Then in your view - you would echo this out inline:
Code:
<html>
<head>
<?= $script; ?>
<style type="text/css"><?= $style; ?></style>
</head>
<body></body>
</html>

That's the only way I could think of doing it - easily... to be honest, it's much easier using relative paths within your scripts and styles than going through this.
#3

[eluser]coolfactor[/eluser]
Not directly, but if you are willing to spare the processing cycles, you could treat CSS and JS files as views.

Say you have an "Assets" controller that has css() and js() functions:
Code:
<link type="text/css" href="/assets/css/styles.css" />

The css() function could:
1) get the full uri: /assets/css/styles.css
2) strip off first 2 segments to be left with: styles.css
3) look for a view file called that.

Code:
function css() {
    // strip off first 2 segments from uri
    $css_file = str_replace('/assets/css/', '', $this->uri->uri_string());
    // assign any variables to the view
    $data['ajax_base_url'] = '/something/here/';
    $data['bg_img_url']     = '/something/else/here/';
    // send appropriate headers
    $this->output->header('Content-Type: text/css');
    // load the processed css file
    $this->load->view($css_file, $data);
}
(example code only)

You could do the same for JavaScript files. Just make sure to pass along the correct headers that the browser is expecting for those files.




Theme © iAndrew 2016 - Forum software by © MyBB