Conditional to detect mobile devices with getUserAgent? I want to create a User Agent check. (Yes I know. It is evil.)

So I created an Array. The whole idea is to see if the user agent contains a specific word. This way I hope to circumvent regex trickery. But I have a hard time figuring how to return true only once:

This would be the array:

{% set browserValues = [ { agent: 'android'}, { agent: 'iemobile'} {# and so on #}]


This is how I get the user agent:

{% set userAgent = craft.request.getUserAgent()|lower %}


I came this far:

 {% for item in browserValues %}
   {% if item.agent in userAgent %}
     You're on mobile
   {% else %}
     You're not on mobile
   {% endif %}
 {% endfor %}


This actually works. But there are two problems: If the conditional is false (not on mobile), the conditional is applied for each key in the array. You're not on mobile You're not on mobile You're not on mobile

If the user agent string contains the word android twice the conditional is applied twice.

How can I prevent the conditional from looping over and over? (My brain starts to loop over and over too).

Thank you.
Unlike in PHP, it's not actually possible to break a for loop in Twig.

To work around that fact, you can use the for loop to set a flag, and then put the conditional outside the loop:

{% set isUserOnMobile = false %}

{% for item in browserValues %}
    {% set isUserOnMobile = not isUserOnMobile ? item.agent in userAgent : isUserOnMobile %}
{% endfor %}

{% if isUserOnMobile %}
    You're on mobile
{% else %}
    You're not on mobile
{% endif %}


Another option: I actually wrote a plugin called Detect for device detection (the plugin wraps the excellent Mobile_Detect library, which is sponsored by BrowserStack). Might be you'll be be able to use that, instead of hard coding lots of user agent strings. Here's how you can use Detect in a template:

{% set isUserMobile = craft.detect.isMobile %}
{% set isUserTablet = craft.detect.isTablet %}
{% set isUserPhone = craft.detect.isPhone %}
{% set isUserIphone = craft.detect.is('iphone') %}
{% set userAgent = craft.detect.getUserAgent %}