How to get complete current url for Cakephp

前端 未结 24 1281
长情又很酷
长情又很酷 2020-12-08 00:10

How do you echo out current URL in Cake\'s view?

24条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 00:52

    I know this post is a little dated, and CakePHP versions have flourished since. In the current (2.1.x) version of CakePHP and even in 1.3.x if I am not mistaken, one can get the current controller/view url like this:

    $this->params['url'];
    

    While this method does NOT return the parameters, it is handy if you want to append parameters to a link when building new URL's. For example, we have the current URL:

    projects/edit/6

    And we want to append a custom parameter action called c_action with a value of remove_image, one could make use of $this->params['url]; and merge it with an array of custom parameter key => value pairs:

    echo $this->Html->link('remove image', array_merge($this->params['url'], array('c_action' => 'remove_image'));
    

    Using the above method we are able to append our custom parameters to the link and not cause a long chain on parameters to build up on the URL, because $this->params['url] only ever returns the controll action URL.

    In the above example we'd need to manually add the ID of 6 back into the URL, so perahaps the final link build would be like this:

    echo $this->Html->link('remove image', array_merge($this->params['url'], array($id,'c_action' => 'remove_image'));
    

    Where $is is a the ID of the project and you would have assigned it to the variable $id at controller level. The new URL will then be:

    projects/edit/6/c_action:remove_image

    Sorry if this is in the slightest unrelated, but I ran across this question when searching for a method to achieve the above and thought others may benefit from it.

提交回复
热议问题