Tag: cakephp static pages

Dealing with static pages v2 (or… 3?)

Over the years of cake development we’ve seen a number of ways to get rid of the the /pages/ path in the URL for static pages.

By default if you create an “about us” page, such as in app/views/pages/about.ctp, the resulting URL would be:
www.example.com/pages/about

I’m sure you’ve seen a ton of complaints and solutions about how to get rid of this seemingly “annoying” /pages/
To keep the URL’s clean, most people would obviously prefer to have www.example.com/about instead. (No /pages/ in sight).

Recently, my favorite solution has become the following setting in the routes.php:

$staticPages = array(
    'about',
    'legal',
    'policy',
    'something'
);

$staticList = implode('|', $staticPages);

Router::connect('/:static', array(
    'plugin' => false,
    'controller' => 'pages',
    'action' => 'display'), array(
        'static' => $staticList,
        'pass' => array('static')
        )
    );

Go ahead, create your about.ctp and then attempt to access it by going to www.yoursite.com/about

The Router will nicely remove the /pages/ from the URL.

Q.
Why keep the pages in the array() and then use implode()? Couldn’t I just have the following?

$staticList = 'about|legal|policy|something';

A.
You sure could, but array structure allows to keep things organized neater and if you have a large amount of pages it’s easier to scan visually to insert/remove pages as necessary. Either way, you have both options to work with.

Get yourself a new home (alternative to home.ctp)

I’m sure you know that to modify your application’s homepage, one needs to edit/create the home.ctp file in app/views/pages/home.ctp.
That, however, leaves you dealing with a more or less static page…

One common option to add some other functionality to your otherwise static pages is to copy the Pages Controller from the core into your app, and make some required modifications.

On the other hand, you don’t have to be stuck with home.ctp as your default main page. All you need to do is simply designate a new root (/) route.

Let’s look at an example…

I have a Markets Controller (markets_controller.php), which has a nice action called summary(). It pulls data from various Market model methods and utilizes some features of the App Controller.
All of that is working quite nicely and in reality I’d prefer that page (summary) to be my new “home”.

So, rather than dealing with Pages Controller hackery, I simply replace the default route (in app/config/routes.php) with:

Router::connect('/', array('controller' => 'markets', 'action' => 'summary'));

That’s it, now I’ve got a new fully dynamic homepage without any pain whatsoever.