Is there any good practice to how to serve mobile pages differently from Twig?

What I would like to achieve is the following, right now we have pages like: http://myawsomecraftpage.com/stories/aaa-bbb-ccc

In the template we are doing many things differently, if the browser is mobile, or not mobile.

I would like to split the template, and have 1 for mobile 1 for desktop. The issue I also would like to cache this pages (ofc differently for mobile, and for desktop)

So the best practice would be to have pages like: http://myawsomecraftpage.com/m/stories/aaa-bbb-ccc

The issue here this is not supported in Craft routing... I mean to generate mobile-aware URL

So another option I guess to add another site right? like http://m.myawsomecraftpage.com/stories/aaa-bbb-ccc

This should work I guess...

So again, the issue here is we have different templates (optimization point of view) for desktop and mobile pages, and we would like to cache them (with bitz for example)

In general, I'd discourage the idea of having separate versions of a page depending on whether it is mobile or not. Typically you can do this more effectively via responsive design, media breakpoints, CSS Grid, and so on.

If you still really want to do it, you can have a conditional like:

{% if craft.app.request.isMobileBrowser() %}
    {% cache using key ("mobile" ~ craft.app.request.pathInfo) %}
        {% include "mobile-page.html" %}
    {% endcache %}
{% else %}
    {% cache using key ("desktop" ~ craft.app.request.pathInfo) %}
        {% include "desktop-page.html" %}
    {% endcache %}
{% endif %}

...but again, the idea of a separate mobile page vs. a desktop page is generally a bit dated these days.

  • This idea is great, but I do not want to load craft at all, I would like to load the nginx files html files which was stored. So I am not planing to use the mobile version (btw that was the solution what we have been used right now, and it is working fine). Reflecting the idea to have different file is oke, but I would like to serve different page for AMP and different page for desktop. Yes we can do it over responsive design, will consider that approach also... – Visky Máté Oct 12 at 3:25
  • As for amp, this might be a good resource google.com/amp/s/nystudio107.com/blog/… – Robin Schambach Oct 12 at 5:34
  • So if you want a different page for AMP, this is how I do it: nystudio107.com/blog/google-amp-should-you-care – andrew.welch Oct 12 at 11:11

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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