Use the right path
The right path to get to a webroot asset in the PluginName plugin is of the form:
/plugin_name/path
I.e.:
- Filepath:
App/Plugin/Corporate/webroot/img/image.png
- Url:
/corporate/img/image.png
In early versions of CakePHP asset dispatching was automatic, while in 2.2+ asset dispatching must be explicitly enabled.
The normal way to deal with plugin assets is to not use the asset dispatch filter and to copy (or symlink) the files to the application webroot in the same path as corresponds to the url i.e.:
cd App
cp -R Plugin/Corporate/webroot webroot/corporate
This means that the url requested directly maps to a file in the application webroot folder - there is no php logic invoked in serving these files which amongst other benefits makes serving such assets significantly faster.
Dealing with paths in javascript
If an application is always, always installed as the root of the domain (http://example.com
) there is absolutely no complexity - just refer to the relative path to the image:
var imagePath = '/corporate/img/image.png';
If however the root of the application is variable (http://example.com/
, http://exmaple.com/sub/folder/
, http://localhost/someproject/
) - it's necessary to tell the javascript what to consider the root of the application. for example put the following in the layout file:
<head>
...
<script>ROOT = '<?= $this->Html->url('/'); ?>';</script>
</head>
<body>
<?= $this->fetch('content'); ?>
...
</body>
In this way, javascript can refer to the global ROOT
anywhere to know what the root url is, like so:
var imagePath = ROOT . 'corporate/img/image.png';
This makes it possible to use the same javascript irrespective of how the application is installed.