我的 CakePHP 插件中有一个 (javascript) 脚本,它在当前查看的文档中创建一个 img
标签。问题是,直到现在,所有提供有效图像源的尝试都失败了。该插件位于 CakePHP 库(不是 CakePHP 应用程序)的插件目录中,因为我们将它用于多个具有很多共同点的独立应用程序。
图像位于 /cake/plugins/Corporate/webroot/img
。
(javascript) 脚本位于 /cake/plugins/Corporate/webroot/js
。
从脚本到图像的相对路径不起作用 (../img/image.png
)。 CakePHP 路由路径 (/Corporate/img/image.png
) 也不起作用,无论我是否在前面加上插件名称都是独立的。
最佳答案
使用正确的路径
在 PluginName 插件中获取 webroot Assets 的正确路径是以下形式:
/plugin_name/path
即:
- 文件路径:
App/Plugin/Corporate/webroot/img/image.png
- 网址:
/corporate/img/image.png
在 CakePHP 的早期版本中, Assets 分配是自动的,而在 2.2+ 中 asset dispatching must be explicitly enabled .
处理插件 Assets 的正常方法是不使用 Assets 调度过滤器并将文件复制(或符号链接(symbolic link))到与 url 对应的相同路径中的应用程序 webroot,即:
cd App
cp -R Plugin/Corporate/webroot webroot/corporate
这意味着所请求的 url 直接映射到应用程序 webroot 文件夹中的文件 - 在提供这些文件时没有调用 php 逻辑,除其他好处外,还可以提供此类 Assets significantly faster .
处理javascript中的路径
如果应用程序始终安装为域的根 (http://example.com
),则绝对没有复杂性 - 只需引用图像的相对路径:
var imagePath = '/corporate/img/image.png';
但是如果应用程序的根是可变的(http://example.com/
,http://exmaple.com/sub/folder/
,http://localhost/someproject/
) - 有必要告诉 javascript 要考虑应用程序的根。例如将以下内容放入布局文件中:
<head>
...
<script>ROOT = '<?= $this->Html->url('/'); ?>';</script>
</head>
<body>
<?= $this->fetch('content'); ?>
...
</body>
这样,javascript 可以在任何地方引用全局ROOT
来知道根url 是什么,如下所示:
var imagePath = ROOT . 'corporate/img/image.png';
这使得无论应用程序如何安装,都可以使用相同的 javascript。
关于javascript - 如何在 CakePHP 中使用插件 javascript 脚本加载插件图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10353132/