"symfony 2 load different template depending on user agent properties" Answer’s

0

Ok, so I don't have a full solution but a little more than where to look for one :)

You can specify loaders (services) for templating item in app/config/config.yml

framework:
    esi:             { enabled: true }
    #translator:     { fallback: %locale% }
    secret:          %secret%
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: %kernel.debug%
    form:            true
    csrf_protection: true
    validation:      { enable_annotations: true }
    templating:       
        engines: 
           - twig 
        loaders:  [moby.loader]
    default_locale:  %locale%
    trust_proxy_headers: false
    session:         ~

Then define the mentioned loader service:

services:
    moby.loader:
        class: AcmeAppBundleTwigLoaderMobyFilesystemLoader
        arguments:    ["@templating.locator", "@service_container"]

After that define your loader service class:

namespace AcmeAppBundleTwigLoader;

use SymfonyBundleFrameworkBundleTemplatingLoaderFilesystemLoader;
use SymfonyComponentTemplatingStorageFileStorage;


class MobyFilesystemLoader extends FilesystemLoader
{
     protected $container;

     public function __construct($templatePathPatterns, $container) 
     {
         parent::__construct($templatePathPatterns);
         $this->container = $container;
     }

     public function load(SymfonyComponentTemplatingTemplateReferenceInterface $template)
     {
         // Here you can filter what you actually want to change from html
         // to mob format
         // ->get('controller') returns the name of a controller
         // ->get('name')  returns the name of the template
         if($template->get('bundle') == 'AcmeAppBundle') 
         {
            $request = $this->container->get('request');
            $format = $this->isMobile($request) ? 'mob' : 'html';

            $template->set('format', $format);
         }

         try {
            $file = $this->locator->locate($template);
         } catch (InvalidArgumentException $e) {
            return false;
         }

         return new FileStorage($file);
      }

      /**
       * Implement your check to see if request is made from mobile platform
       */
       private function isMobile($request)
       {
           return true;
       }
 }

As you can see this isn't the full solution, but I hope that this, at least, points you to the right direction.

EDIT: Just found out that there is a bundle with mobile detection capabilities, with custom twig engine that renders template file depending on a device that sent request ZenstruckMobileBundle, although I never used it so... :)

Wednesday, March 31, 2021
 
csi
answered 10 Months ago
csi
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share