2

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.

6

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 %}
| improve this answer | |
  • +1 for using a plugin for this problem. – carlcs Feb 9 '16 at 11:28
  • Is there a way to check if this is an iPhoneX (as opposed to other versions of iPhone)? I tried {{ craft.mobileDetect.version('iPhone') }} but just get a 1. Thanks. – userAW Nov 21 '19 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.