skip to Main Content

I’m developing a site on a platform that’s using the Twig (Symfony) language for its templates, and in one place, I need to change the layout (disable a default block and load a different block) based on whether the user is on a mobile device or a desktop.

I know how to do it in PHP (using the “check_user_agent(‘mobile’)” variable), but that doesn’t work in Twig… and I’ve come across a reference to the Twig “Mobile Detect Bundle”, but I have no idea how to install it (shared hosting with cPanel).

Soo… is there a way to detect mobile user-agent in Twig, without having to install anything?

3

Answers


  1. If you already have PHP code to return true/false based on the user agent, it is quite simple to Write a custom Twig Extension to run that code, but from Twig.

    Alternatively, you can run the check in the controller and pass in the result, or in a ‘kernel.controller Event’ to even run the check before a controller action is called (probably putting it into a Request ‘attributes’, where it can also be checked in the template).

    Login or Signup to reply.
  2. During each request, Symfony will set a global template variable app in both Twig and PHP template engines by default.
    The Request object that represents the current request: app.request

    So if you want to know the user-agent you can use app.request.headers in the template.
    e.g :

    {{ app.request.headers.get('User-Agent')}}
    
    Login or Signup to reply.
  3. General Solution for PHP

    https://github.com/serbanghita/Mobile-Detect/ is a great and maintained php class to detect the user agent and is not limited to Symfony.

    For Symfony

    To use the above class with Symfony, you could either write a twig extension yourself or use this Mobile Detect Twig Extension that does the job.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search