CakePHP 3: Add specific JS/CSS file to a specific view

14,260

Solution 1

Go to your index.ctp file and insert this code at the bottom.

For JS

echo $this->Html->script('/otherdir/scripts');

or

echo $this->Html->script('http://code.jquery.com/jquery.min.js');

Will output:

<script src="http://code.jquery.com/jquery.min.js"></script>

The first parameter can be an array to include multiple files.

echo $this->Html->script(['jquery', 'wysiwyg', 'scripts']);

Will output:

<script src="/js/jquery.js"></script>
<script src="/js/wysiwyg.js"></script>
<script src="/js/scripts.js"></script>

You can append the script tag to a specific block using the block option:

echo $this->Html->script('wysiwyg', ['block' => 'scriptBottom']);

Then, in your layout, make sure to have the said block so they get outputted:

<?= $this->fetch('scriptBottom')?>

For CSS

This method of CSS inclusion assumes that the CSS file specified resides inside the webroot/css directory if path doesn’t start with a ‘/’.

echo $this->Html->css('forms');

Will output:

<link rel="stylesheet" href="/css/forms.css" />

The first parameter can be an array to include multiple files.

echo $this->Html->css(['forms', 'tables', 'menu']);

Will output:

<link rel="stylesheet" href="/css/forms.css" />
<link rel="stylesheet" href="/css/tables.css" />
<link rel="stylesheet" href="/css/menu.css" />

Solution 2

<?php echo $this->Html->css('style.css',['block'=>true]); ?>

The block = true option causes the css to load inside the head tag. It will be loaded where you put the code <?php echo $ this-> fetch ('css'); ?> in your template

Share:
14,260
Victor
Author by

Victor

Updated on June 30, 2022

Comments

  • Victor
    Victor almost 2 years

    I'm using CakePHP 3.3.10. I need to add a JavaScript file to a specific view.

    // default.ctp  
    // I need to remove this script in default.ctp and load only in a specific view.  
    
    <?= $this->Html->script(['otherfile.js', 'otherfile.js', folder/scripts.js']) ?>  
    

    How can I load the js file only in this view?:

    // index.ctp  
    // I need to load the scripts.js file only in this view
    
  • karim_fci
    karim_fci over 6 years
    In my case, output new line not work? like following <link rel="stylesheet" href="/css/forms.css" /><link rel="stylesheet" href="/css/tables.css" /><link rel="stylesheet" href="/css/menu.css" /> How can i solve this?