Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - determine if mobile agent or not

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?

like image 580
TomJones999 Avatar asked Oct 07 '17 20:10

TomJones999


2 Answers

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.

like image 182
Niket Pathak Avatar answered Oct 31 '22 16:10

Niket Pathak


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')}}
like image 1
Samuel NELA Avatar answered Oct 31 '22 15:10

Samuel NELA