我像这样为我的网站自定义了基本路径:
Router::scope('/', function (RouteBuilder $routes) {
//$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
//My custom base path
$routes->connect('/', ['controller' => 'Posts', 'action' => 'index', 'home']);
//Connect the rest of PagesController URLs
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
//I don't quite understand what this line does
$routes->fallbacks(DashedRoute::class);
});
然后,当我在控制器内重定向时,URL 是正确的,如下所示:
return $this->redirect(['controller' => 'Posts', 'action' => 'view', $data['post_id']]);
//output:
// localhost/jayblog/posts/view/2
但是对于外部链接和WWWROOT
,它会返回错误的:
<li><a href="https://www.example.com" target="_blank" title="Twitter">LINK</a></li>
//output is wrong:
// localhost/jayblog/https://www.example.com
<?= $this->Html->image(WWW_ROOT.DS.'files'.DS.$photos[$i]->file_name); ?>
//output:
// jayblogD:pathtofile.PNG
任何人都可以建议我如何解决问题。谢谢!
因为WWW_ROOT是绝对文件系统路径,而不是像 HTML::image 期望的相对路径。这永远不会起作用:
<?= $this->Html->image(WWW_ROOT.DS.'files'.DS.$photos[$i]->file_name); ?>
调试您的变量并查看发生了什么,例如
var_dump(WWW_ROOT);
请查看 Html::image() 文档 https://book.cakephp.org/3.0/en/views/helpers/html.html#linking-to-images 并传递给它一个数组,例如文档请求,或者在您的情况下更可能是这样的:
<?= $this->Html->image('/photos-directory/'.$photos[$i]->file_name); ?>
照片目录可能存在于类似/var/www/your-project/photos-directory 中的地方
试试下面的这个替换
$routes->fallbacks(DashedRoute::class); to $routes->fallbacks('InflectedRoute');
<?php
use CakeCorePlugin;
use CakeRoutingRouter;
Router::defaultRouteClass('Route');
Router::scope('/', function ($routes) {
$routes->connect('/', ['controller' => 'Pages', 'action' => 'display', 'home']);
$routes->connect('/pages/*', ['controller' => 'Pages', 'action' => 'display']);
$routes->fallbacks('InflectedRoute');
});
Router::extensions('json', 'xml');
/**
* Load all plugin routes. See the Plugin documentation on
* how to customize the loading of plugin routes.
*/
Plugin::routes();
?>
它对我有用。
<ul>
<li><a href="http://www.cakephp.org/" target="_blank">
<?php echo $this->Html->image('technology-use/cakephp.jpg', array('alt' => 'images'));?></a></li>
</ul>