Symfony 2 load different template depending on user agent properties

后端 未结 8 1368
时光取名叫无心
时光取名叫无心 2020-12-02 17:28

Is it possible (and how) to

  • determine if a user is using a mobile device
  • force symfony 2 to load different template in that case
  • <
相关标签:
8条回答
  • 2020-12-02 18:03

    This is what did the trick for me in Symfony 2.0:

    Override twig.loader service so we can set our custom class:

    twig.loader:
        class: Acme\AppBundle\TwigLoader\MobileFilesystemLoader
        arguments:
            locator:  "@templating.locator"
            parser:   "@templating.name_parser"
    

    And create our custom class, that just sets "mob" format to the templates in case the client is a mobile device:

    namespace Acme\AppBundle\TwigLoader;
    
    use Symfony\Bundle\TwigBundle\Loader\FilesystemLoader;
    
    class MobileFilesystemLoader extends FilesystemLoader
    {
    
        public function findTemplate($template)
        {
            if ($this->isMobile()) {
                $template->set('format', 'mob');
            }
    
            return parent::findTemplate($template);
         }
    
    
        private function isMobile()
        {
            //do whatever to detect it
        }
     }
    
    0 讨论(0)
  • 2020-12-02 18:05

    I would suggest that this is not best handled by the controller but by CSS media queries, and serving a separate stylesheet to different classes of devices based on the results of that CSS media query. A good intro here: http://www.adobe.com/devnet/dreamweaver/articles/introducing-media-queries.html

    and I would try reading http://www.abookapart.com/products/responsive-web-design in great detail. Some thinking has been done since the book was published, but it will get you headed the right direction.

    0 讨论(0)
提交回复
热议问题