How to detect the device in Smarty for PrestaShop 1.7 in a TPL?

Mobile, tablet or computer, offer the right display to your customers with Smarty on PrestaShop

When developing a store design, you may want to customize the display based on the medium that will be used to view it, a cell phone, tablet or computer.

PrestaShop integrates this information easily to avoid having to implement a third-party solution that will not be maintained over time.

The template engine used by PrestaShop is Smarty, and although many newcomers find it outdated or obsolete, it is often because they do not know it and have difficulty learning it, as with any new technology. The choice of PrestaShop to stay on this template engine allows a very interesting compatibility between versions.

Without further ado, I reveal the simple code to use in any TPL file of your theme or module to quickly identify the device used by your store visitors.

{if Context::getContext()->isMobile() == 1}
    {if Context::getContext()->getDevice() != 2}
        // Tablet
    {else}
        // Cell phone
    {/if}
{else}
    // Computer
{/if}

There are other alternatives, which I find less practical, but more readable, such as

{if Context::getContext()->isTablet()}
    // Tablet
{else if  Context::getContext()->isMobile()}
    // Cell phone
{else}
    // Computer
{/if}

On the other hand, when developing a module, I would always advise you to perform this kind of test in PHP rather than in your Smarty TPL, the performance will be better.

So, you just have to pass this information in a variable to your template to use it as you wish.

In the same way, the choice of testing the type of device rather than using CSS customization with the Media Query, can be justified in the context of improving performance by preventing the loading of large files, especially if they should not be displayed.

And this is where we can ask ourselves if the choice to do everything in responsive rather than having a theme adapted on mobile is the best solution.

Comments