Add a Static Page to Symfony

Mon, Mar 28, 2011 2-minute read

Static pages can be added to Symfony quite easily.

Edit your routing.yml file which is probably located at apps/frontend/config/routing.yml, and add the following routes to add an about, a privacy, and a terms and conditions page.

# static pages
about:
  url:   /about
  param: { module: home, action: page, view: about }
privacy:
  url:   /privacy
  param: { module: home, action: page, view: privacy }
terms:
  url:   /terms
  param: { module: home, action: page, view: terms }

If you are going to keep the generic rules, make sure you add these new rules before the default actions.

Clear your cache:

./symfony clear-cache

Then inside the module named home (create it if it doesn’t exist), add the following action:

/**
 * Load a static page.
 * @param sfRequest $request A request object
 */
public function executePage(sfWebRequest $request)
{
  $directory = $this->getContext()->getModuleDirectory().DIRECTORY_SEPARATOR."templates";
  $name = $request->getParameter('view');
  // for safety, strip out all non-alphanumeric characters
  $name = preg_replace('/[^a-zA-Z0-9\s]/', '', $name);
  if (is_readable($directory.DIRECTORY_SEPARATOR.$name."Success.php"))
  {
    return $this->setTemplate($name);
  }
  else
  {
    $this->forward404();
  }
}

The template files will be on the home/templates directory, called aboutSuccess.php, privacySuccess.php, and termsSuccess.php

This action will check if the template file exists, and if so load the template, if not it will forward to the 404 not found page. Easy and safe static templates. Add more routes and the appropriate template file as required.