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?
https://github.com/serbanghita/Mobile-Detect/ is a great and maintained php class to detect the user agent and is not limited to 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.
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')}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With