Add an i18n Static Page to Symfony

Mon, May 16, 2011 2-minute read

My last post explained the basics on how to add static pages in symfony, this post expands on that and shows you how to do it for a multilingual site.

We split the template finding code out for code maintainability, and we enhance it on where to look for the file. First it tries to find the template in the language and country eg: en_CA, then it tries to find the template in the matching language, and if that is not found, it falls back to the default language.

/**
 * Load a static page.
 * @param sfRequest $request A request object
 */
public function executePage(sfWebRequest $request)
{
  $template = $this->findTemplate($request->getParameter('view'), $this->getUser()->getCulture());
  $this->forward404Unless($template);
  $this->setTemplate($template);
}

/**
 * Check if a template page exists for a given culture.
 * Be intelligent and check if language & country exist, try language, and then default to english.
 * @param string $name Template filename to check
 * @param string $culture Symfony culture string
 */
protected function findTemplate($name, $culture)
{
  // for safety, strip out all non-alphanumeric characters
  $name = preg_replace('/[^a-zA-Z0-9\s]/', '', $name);

  $directory = $this->getContext()->getModuleDirectory() . DIRECTORY_SEPARATOR ."templates";
  // try language and country: en_CA
  if (is_readable($directory . DIRECTORY_SEPARATOR . $culture. DIRECTORY_SEPARATOR . $name ."Success.php"))
  {
    return $culture. DIRECTORY_SEPARATOR . $name;
  }
  // try langage only: en
  elseif (is_readable($directory . DIRECTORY_SEPARATOR . substr($culture, 0, 2). DIRECTORY_SEPARATOR . $name ."Success.php"))
  {
    return substr($culture, 0, 2). DIRECTORY_SEPARATOR . $name;
  }
  // try default language
  elseif (is_readable($directory . DIRECTORY_SEPARATOR . $name ."Success.php"))
  {
    return $name;
  }
  return false;
}

The template directory should have the default language file as usual, eg: templates/helpSuccess.php, and then there should be folders for each language and possibly language & country with the same filename, but localized. eg: templates/fr/helpSuccess.php