2

在我的 CakePHP 应用程序中,我连接了以下路由:

Router::connect('/:city/dealer/:id', 
    array('controller' => 'dealers', 'action' => 'view'),
    array(
        'pass' => array('city', 'id'),
        'city' => '[a-z]+',
        'id' => '[0-9]+'
        )
    );

这很好用并且可以启用:domain.com/washington/dealer/1

但是如何在视图中为这个 URL 生成正确的 HTML 链接呢?如果我这样做:

echo $this->Html->link(
    'Testlink',
    array('washington', 'controller' => 'dealers', 'action' => 'view', 1)
);

它将所有参数添加到生成链接的末尾:

http://domain.com/dealers/view/washington/1

我该如何正确地做到这一点?

4

2 回答 2

2

我相信您仍然需要指定参数,如下所示:

echo $this->Html->link('Testlink',
    array('controller' => 'dealers', 'action' => 'view', 'city' => 'washington',
                                                         'id'=> 1));

Cake 在食谱中有一个类似的例子:

<?php
// SomeController.php
public function view($articleId = null, $slug = null) {
    // some code here...
}

// routes.php
Router::connect(
    '/blog/:id-:slug', // E.g. /blog/3-CakePHP_Rocks
    array('controller' => 'blog', 'action' => 'view'),
    array(
        // order matters since this will simply map ":id" to $articleId in your action
        'pass' => array('id', 'slug'),
        'id' => '[0-9]+'
    )
);

// view.ctp
// this will return a link to /blog/3-CakePHP_Rocks
<?php
echo $this->Html->link('CakePHP Rocks', array(
    'controller' => 'blog',
    'action' => 'view',
    'id' => 3,
    'slug' => 'CakePHP_Rocks'
));
于 2012-10-08T15:08:05.717 回答
0

嗨,塞巴斯蒂安,它可能为时已晚,无法帮助您,但我也许可以帮助其他人解决这个问题。解决问题的关键是在 Helper 类中添加 url 方法。我通过在 View/Helper 中创建 AppHelper.php 来做到这一点。它看起来像这样。我为你的城市改变了我的参数。

查看/Helper/AppHelper.php

<?php
App::uses('Helper', 'View');
class AppHelper extends Helper {

    function url($url = null, $full = false) { 
            if (is_array($url)) { 
                   if (empty($url['city']) && isset($this->params['city'])) { 
                            $url['city'] = $this->params['city']; 
                    }

                    if (empty($url['controller']) && isset($this->params['controller'])) { 
                            $url['controller'] = $this->params['controller']; 
                    }

                    if (empty($url['action']) && isset($this->params['action'])) { 
                            $url['action'] = $this->params['action']; 
                    }
            } 

            return parent::url($url, $full); 
    }

 }
 ?>

然后我创建像

Router::connect('/:city/dealer/:id', 
array('controller' => 'dealers', 'action' => 'view', 'id'=>':id'),
array('pass' => array('city', 'id'),
      'city' => '[a-z]+',
      'id' => '[0-9]+'
));

希望这可以帮助 :)

于 2013-03-27T17:47:01.173 回答