Html 帮助程序 link 嵌套资源路由

Html helper link to nested resource Routes

我有以下路线:

$routes->resources('Articles', function ($routes) {
    $routes->resources('Comments');
});

我想link对id为4的文章的所有评论:

articles/4/comments

如何使用 cakes HtmlHelper 为这个 url 创建一个 link?

有关嵌套路由的更多信息: https://book.cakephp.org/3.0/en/development/routing.html#creating-nested-resource-routes

您可以像这样加入 Html 和 Url 助手:

<?= 
    $this->Html->link(
        'Enter',
        $this->Url->build('/articles/4/comments', true),
        ['class' => 'button', 'target' => '_blank']
    ); 
?>

另请参阅:

查看链接文档中给出的示例路由模式,嵌套的 Articles > Comments 资源将为 Comments 创建具有以下模式的路由:

/articles/:article_id/comments
/articles/:article_id/comments/:id

您还可以检查 $ bin/cake routes 以获取所有已连接路由及其模式和默认值的列表。您正在寻找的路线将列在那里,如下所示:

+----------------+--------------------------------+--------------------------------------------------------------------------+
| Route name     | URI template                   | Defaults                                                                 |
+----------------+--------------------------------+--------------------------------------------------------------------------+
| comments:index | /articles/:article_id/comments | {"controller":"Comments","action":"index","_method":"GET","plugin":null} |

所有资源路由都绑定了特定的HTTP方法(如上defaults栏中可见),即内部使用了_method选项,parent ID以单数[=52]为前缀=] 名字.

要匹配 Comments 索引,只需照常定位 Comments 控制器和 index 操作。另外传递相应的 _method(对于 indexGET),并以命名方式传递父 ID,即 article_id,例如:

[
    'controller' => 'Comments',
    'action' => 'index',
    '_method' => 'GET',
    'article_id' => 4
]

另见