Twig - determine if mobile agent or not
Asked Answered
S

4

11

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?

Simmer answered 7/10, 2017 at 20:38 Comment(0)
W
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.

Wampumpeag answered 3/7, 2019 at 10:35 Comment(0)
S
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')}}
Semitropical answered 7/10, 2017 at 21:25 Comment(0)
B
0

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).

Brandiebrandise answered 7/10, 2017 at 21:20 Comment(1)
I think @snela, @alisterbulman is right... You can resolve your problem with Twig Extension.Weigh
L
0

If you dont want to use the Mobile Detect Bundle and you want to detect mobile in Twig here is a solution:

    {% if 'iPhone' in app.request.headers.get('User-Agent') 
        or 'iPod' in app.request.headers.get('User-Agent') 
        or 'iPad' in app.request.headers.get('User-Agent') 
        or 'Android' in app.request.headers.get('User-Agent') 
        or 'BlackBerry' in app.request.headers.get('User-Agent') %}
            <h1>Hi, I see this using Mobile Device</h1>
    {% else %}
            <h1>Hi, I see this because im not using Mobile Device</h1>
    {% endif %}
Laevo answered 11/9, 2023 at 6:9 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.