Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I append .html to all my URLs in cakephp?

I am using cakephp in one of my projects and my client wants the site URLs to end with .html and not the usual friendly urls. I was wondering if its possible in cakephp to do so through any of its routing techniques. Please help.

like image 533
Atul Dravid Avatar asked Aug 04 '10 23:08

Atul Dravid


4 Answers

That is well documented in the cookbook.

UPDATE: http://book.cakephp.org/2.0/en/development/routing.html#file-extensions

To handle different file extensions with your routes, you need one extra line in your routes config file:

Router::parseExtensions('html', 'rss');

If you want to create a URL such as /page/title-of-page.html you would create your route as illustrated below:

Router::connect(
    '/page/:title',
    array('controller' => 'pages', 'action' => 'view'),
    array(
        'pass' => array('title')
    )
);

Then to create links which map back to the routes simply use:

$this->Html->link(
    'Link title',
    array('controller' => 'pages', 'action' => 'view', 
          'title' => 'super-article', 'ext' => 'html')
);
like image 86
bancer Avatar answered Oct 22 '22 18:10

bancer


One of the parameters you can send to Router::url() (which is called by other methods like HtmlHelper::link() and Controller::redirect()) is 'ext'. Try setting this to 'html'. E.g:

echo $this->Html->link('Products', array('controller' => 'products', 'action' => 'index', 'ext' => 'html'));

or

$this->redirect(array('controller' => 'products', 'action' => 'index', 'ext' => 'html'));

If it works, try figuring out a way you can override Router::url() to add it in by default.

like image 40
neilcrookes Avatar answered Oct 22 '22 19:10

neilcrookes


Had to solve this without using Routes. Kept the default route entry for pages:

Router::connect('/pages/*', array('controller' => 'pages', 'action' => 'display'));

and in the display action removed the .html extension and rendered the respective view:

preg_replace('/\.html$/','',$view);
$this->render(null,'default',$view);

While calling the pages added 'ext' to be .html

like image 21
Atul Dravid Avatar answered Oct 22 '22 18:10

Atul Dravid


According to this page you can do something like this

Router::connect('/(.*).html', array('controller' => 'pages', 'action' => 'display'));

but as you are talking about extensions, that may have other consequences.

like image 34
µBio Avatar answered Oct 22 '22 20:10

µBio