I'm using the JsHelper to write JS links to use ajax to load in a page. Like this:
<?= $this->Js->link($item['Series']['title'], array(
'controller' => 'series',
'action' => 'view',
$item['Series']['id']
), array('update' => '#menu-items')); ?>
This is working fine, but now I'd like to add it so that you can link to these pages. So, for example, when you click the link it would redirect you to example.com/#!/series/2
. You could then also go to this url and the correct page would be loaded in the #menu-items
div.
Is this something I'd have to write from scratch, or is there a CakePHP helper or plugin available that would do it for me? I have experience in doing something like this before, but never with CakePHP and unsure where to start.
Thanks,
I've had a go at tackling it myself now, as I figured that as there was no response then something like this wasn't already built for CakePHP.
So first, the javascript:
What this does is check to see if the
location.hash
has changed, if it has, then it checks to see if it starts with#!/
. (I.e#!/:controller/:action/:id
is the hash that I'm looking for). It then just calls the jQuery load function to load that controller and action.I then had to modify my links to use the
url
method in theHtmlHelper
.This creates a string for the controller and action, then appends it to
#!
in thelink
method. Doing it this way, may seem quite long winded (You could probably write a custom helper to make it one line) but it allows you to change the URLs in theconfig/routes.php
later on. You end up with a url like this:#!/categories/view/2
Lastly, you need to make sure that in your controllers you have this at the end of each of method you use.
I'm not imagining that this is a perfect solution, but it does the job quite nicely at the moment. Open to suggestions for improvement too.
There are open source projects that may be able to help you along. Here's a good starting point: https://github.com/browserstate/history.js