Code snippets for symfony 1.x

Navigation

Culture-aware templates

The following view class tries to load the template under directory name of the current culture, then fall back to the default template if such template cannot be found.

So if you access to "index" action of module "foo" and if current user culture is "zh_HK", the class will try to load: "module/foo/templates/zh_HK/indexSuccess.php"

If no such file exist, it will fall back to the default behaviour by loading "module/foo/templates/indexSuccess.php"

class sfCulturePHPView extends sfPHPView
{
  protected
    $cultureDirectory = '';
 
  public function initialize($context, $moduleName, $actionName, $viewName)
  {
    parent::initialize($context, $moduleName, $actionName, $viewName);
  }
 
  public function getDirectory()
  {
    if ($this->cultureDirectory)
      return $this->directory.'/'.$this->cultureDirectory;
    return $this->directory;
  }
 
  protected function preRenderCheck()
  {
    parent::preRenderCheck();
 
    // determine whether the culture-aware template is usable
    $currentCulture = $this->context->getUser()->getCulture();
 
    $template = $this->directory.'/'.$currentCulture.'/'.$this->template;
 
    if (is_readable($template))
      $this->cultureDirectory = $currentCulture;
    else
      $this->cultureDirectory = '';
  }
}
 
by Tamcy on 2008-05-27, tagged culture  view 

Comments on this snippet

gravatar icon
#1 excessive demon on 2008-09-23 at 12:54

Though a nice snippet and idea, I would still refrain from using it. If you have a fair share of languages, creating different template files would only mess up your code's maintainability later on. What's wrong with adding a nice 'if' in your code? You can include a different partial if you wish. Adding the is_readable() is a call wasteful to the filesystem.