0

有关信息,我目前正在从事的项目是 Symfony 2.3

我有一个名为DeviceListener检查我的用户设备的事件侦听器。(它使用MobileDetect类)

我必须指向一个文件夹,其中有与该设备相关的模板(以手机为例)

目前我的事件监听器工作,可以查看我的用户是在智能手机上还是在桌面上,并且可以找到我的Mobile文件夹。但无法弥补模板。

这是我在侦听器中的工作代码

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);
        }
    }
}

和我设置的 service.yml:

app.device_listener:
            class: AppBundle\EventListener\DeviceListener
            arguments:
                - @twig.loader.filesystem
                - @session
            tags:
                - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest}

如您所见,我正在使用onKernelRequest,但我想使用onKernelView可能是更好的解决方案。

出于测试目的,我在我Resources/views的 Mobile 文件夹中创建了包含移动设备的模板。

AppBundle
    |
     -Resources
       |
       - views
         |
         - Mobile
         | |
         | - index.html.twig
         - someView.html.twig
         - someView.html.twig

我的模板

{% extends '@AppBundle/layout.html.twig' %}

{% block body %}
    <p>This template is exclusively for mobile !</p>
{% endblock %}

有任何想法吗?

4

0 回答 0