Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "filter environment"

Environment-dependent layouts (themes)

A possible way to implement themes in symfony is to use a different layout depending on the environment that is active. Although that's obviously not the original purpose of symfony's environment model, this solution offers great flexibility which is actually superior to regular themes. It is superior because you may have your page completely rearranged and layouted differently without changing one single line of code in your actions.

Let's say we have a website which shall be displayed nicely on mobile devices as well. For this purpose we create two environments: 'frontend' and 'mobile' (names are arbitrary).

We add the following filter class to the /lib directory of our application:

class myEnvironmentLayoutFilter extends sfFilter {
 
    public function execute($filterChain) {
 
        switch (SF_ENVIRONMENT) {
            case 'frontend':
                $this->getContext()->getController()->getActionStack()->getFirstEntry()->getActionInstance()->setLayout('layout_frontend');
                break;
            case 'mobile':
                $this->getContext()->getController()->getActionStack()->getFirstEntry()->getActionInstance()->setLayout('layout_mobile');
                break;
        }
 
        $filterChain->execute();
 
        switch (SF_ENVIRONMENT) {
            case 'frontend':
                $this->getContext()->getResponse()->addStyleSheet('frontend');
                break;
            case 'mobile':
                $this->getContext()->getResponse()->addStyleSheet('mobile');
                break;
        }
 
    }
}

Note the environment-dependent style sheets.

And in filters.yml:

# generally, you will want to insert your own filters here
 
myEnvironmentLayoutFilter:
  class: myEnvironmentLayoutFilter

The advantages should be obvious: performance, as no filesystem access is necessary (no need to check for certain directories or template files). flexibility and expandability - features can be easily added to just one theme/layout, components can be arranged as needed, feature-stripped versions of a website may be realized, too. Less redundant template code. Easy to maintain.

by dante on 2007-06-14, tagged environment  filter  layout  themes