I started using libraries like jQuery or Twitter Bootstrap with composer. Now I want to load the jquery.min.js
from /vendor/components/jquery/
into my /src/Template/Layout/default.ctp
.
How can I do that?
Because using a normal uri doesn’t work:
<script type="text/javascript" src="/vendor/components/jquery/jquery.min.js"></script>
Cake doesn’t interpret the file as a file. It looks for a Controller:
Error: VendorController could not be found.
How can I load the JS-file properly?
2
Answers
You should place all your
js
in/webroot/js
folder. You can use it inline by using:this would load :
<script src="/js/jquery.min.js"></script>
This question is perhaps a little broad, but you probably want to look into using something like Gulp or Webpack to build your assets from the Composer files to your app’s webroot. These will also enable you to concatenate and minimise all your JS/CSS assets to improve performance. Although personally I’d probably use a CDN to deliver a library like jQuery as it is so commonly used on the web that you can benefit from cross-site caching.
The reason why you are getting an error like “Error: VendorController could not be found.” is because Cake can’t find the ‘vendor’ directory inside ‘webroot’ so is looking for a Controller instead due to the way it handles magic routes (this bit in the routes.php file
$routes->fallbacks('DashedRoute');
).If you don’t want to use a tool like Gulp or Webpack you could symlink the relevant files in your webroot folder, but personally I’d use my initial suggestions as these will give you many other benefits. If you do symlink just make sure you don’t symlink the entire vendor directory as you don’t want to expose all the code in there.