【问题标题】:Html helper link to nested resource Routes指向嵌套资源路由的 Html 帮助程序链接
【发布时间】:2017-05-30 11:55:24
【问题描述】:

我有以下路线:

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

我要链接到id为4的文章的所有cmets:

articles/4/comments

如何使用 cakes HtmlHelper 创建指向此 url 的链接?

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

【问题讨论】:

    标签: php cakephp url-routing cakephp-3.0


    【解决方案1】:

    查看链接文档中给出的示例路由模式,嵌套的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 方法(可以在上面的默认列中看到),即在内部使用 _method 选项,并且父 ID 以单数控制器/资源名称为前缀。

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

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

    另见

    【讨论】:

    • 非常感谢!解决办法就是这么简单
    【解决方案2】:

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

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

    另见:

    【讨论】:

      猜你喜欢
      • 2015-06-30
      • 2019-07-07
      • 1970-01-01
      • 2016-09-17
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多