For info, the project i'm currently working on is on Symfony 2.3
I have an event listener called DeviceListener
checking my user device. (it uses the MobileDetect class)
I must point to a folder where there is templates affiliated with that device (mobiles as an example)
At the moment my eventlistener works and can see if my user is on a smartphone or on desktop and can locate my Mobile
folder. But couldn't make up to the template.
Here is my working code in the listener
namespace AppBundle\EventListener;
use Mobile_Detect;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class DeviceListener
{
/**
* Twig Loader
* @var \Twig_Loader_Filesystem
*/
protected $loader;
/**
* @var Session
*/
protected $session;
/**
* DeviceListener constructor.
* @param \Twig_Loader_Filesystem $loader
*/
public function __construct(\Twig_Loader_Filesystem $loader, Session $session)
{
$this->loader = $loader;
$this->session = $session;
}
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
$device = $event->getRequest()->headers->get('User-Agent');
$class = new Mobile_Detect();
$mobile = $class->isMobile($device);
$path_mobile = sprintf('%s/../Resources/views/Mobile', __DIR__);
if ($mobile) {
$this->loader->prependPath($path_mobile);
}
}
}
and the service.yml I setted up:
app.device_listener:
class: AppBundle\EventListener\DeviceListener
arguments:
- @twig.loader.filesystem
- @session
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest}
As you can see i'm using onKernelRequest
but I guess that using onKernelView
might be a better solution.
And for test purpose I created in my Resources/views
my Mobile folder containing templates for mobile devices.
AppBundle
|
-Resources
|
- views
|
- Mobile
| |
| - index.html.twig
- someView.html.twig
- someView.html.twig
My template
{% extends '@AppBundle/layout.html.twig' %}
{% block body %}
<p>This template is exclusively for mobile !</p>
{% endblock %}
Any ideas?