Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP linking css files and javascript files

Tags:

cakephp

How do you link css files and javascript/jquery files to a controller/view??

I am using CakePHP_1.3 and have located the following code online, but I cant seem to figure out where to put this, and secondly, where to place the css file named css_file.

<?php $this->Html->css("css_file", null, array("inline"=>false)); ?>

Any help appreciated guys...

like image 505
Donal.Lynch.Msc Avatar asked Jul 27 '11 17:07

Donal.Lynch.Msc


3 Answers

You would put the CSS file in:

app/
  webroot/
      css/ <-- here

You would put the line of code in your default.ctp layout. This is located in (1.3):

cake/
  libs/
      view/
        layouts/
          default.ctp <-- copy this to app/views/layouts/

Then open that up app/views/layouts/default.ctp and look at the HTML. You'll see where Cake is already using this command. Simply replace the filename with the file you added. Do not add the .css to the end when you add the line of code.

like image 168
Charles Sprayberry Avatar answered Sep 21 '22 14:09

Charles Sprayberry


you use echo $this->Html->css('css_file_name_without_the_extension'); and echo $this->Html->script('same') in the view

like image 24
Anh Pham Avatar answered Sep 22 '22 14:09

Anh Pham


Based on your question, it sounds like you were asking how to do this on a view-by-view basis.

This is where $scripts_for_layout comes in useful.

You just need to make sure that it's in your <head> tag in /app/views/layouts/default.ctp as <?php echo $scripts_for_layout; ?>

Then, you can literally add the code you included in your question into any of your views, at literally any point you like. Because you have 'inline' => false it won't actually appear at that position in the view:

<?php $this->Html->css("css_file", null, array("inline"=>false)); ?>

...and you'll find that css_file.css is automatically linked in your <head> whenever that particular view is loaded. This is a great way to only load specific CSS files on a per-view basis when they're needed, yet make sure they appear in the <head> tag where they should be.

This also works for JavaScript as follows:

<?php $this->Html->script("js_file", null, array("inline"=>false)); ?>

If you want to have one or more CSS files loaded in all views, just put a shortened version your code in the <head> of default.ctp as follows:

<?php echo $html->css(array('each','one','of','your','css','files'));

Or, again, for JavaScript:

<?php echo $html->script(array('each','one','of','your','js','files'));

Don't include the .css or .js extension in the array.

like image 31
Joseph Avatar answered Sep 19 '22 14:09

Joseph