MobileDetect

Компонент для создания мобильной версии страниц сайта.
Версия 2.1.0-pl
Дата выпуска 02.09.2026
Загрузки 3 644
Просмотры 21 195
Компонент позволяет определять тип устройства пользователя и выводить контент в зависимости от этого. Всего возможно 3 типа вызова.

1. Как фильтр Fenom
{if 'standard' | mobiledetect}
    <p>This is a <b>standard</b> view via Fenom output filter.</p>
{/if}

{if 'tablet' | mobiledetect}
    <p>This is a <b>tablet</b> view via Fenom output filter.</p>
{/if}

{if 'mobile' | mobiledetect}
    <p>This is a <b>mobile</b> view via Fenom output filter.</p>
{/if}
Этот способ является самым лучшим, но подходит только если вы используете парсинг всех страниц сайта через Fenom.
В отличии от двух следующих типов вызова, код в неподходящих блоках выполняться не будет, что даёт возможность вызывать в них какие-то сниппеты.

2. Как блоковая функция Fenom
{standard}
    <p>This is a <b>standard</b> view via Fenom output filter.</p>
{/standard}

{tablet}
    <p>This is a <b>tablet</b> view via Fenom output filter.</p>
{/tablet}

{mobile}
    <p>This is a <b>mobile</b> view via Fenom output filter.</p>
{/mobile}
{mobile}{/mobile} — телефоны и планшеты
{desktop}{/desktop} — десктоп
{standard}{/standard} — десктоп
{phone}{/phone} — только телефоны
{tablet}{/tablet} — только планшеты

3. Как сниппет MODX
[[!MobileDetect:is=`1`:then=`
    <p>This is a <b>standard</b> view via Snippet tag.</p>
`:else=``?input=`standard`]]

[[!MobileDetect:is=`1`:then=`
    <p>This is a <b>tablet</b> view via Snippet tag.</p>
`:else=``?input=`tablet`]]

[[!MobileDetect:is=`1`:then=`
    <p>This is a <b>mobile</b> view via Snippet tag.</p>
`:else=``?input=`mobile`]]
Cниппет сравнивает тип устройства в параметре &input с тем, что у пользователя, и возвращает 1 или 0, которые можно проверять. Будет работать везде, но вид записи не самый удобный.

4. Как HTML теги не рекомендуется
<standard>
    <p>This is a <b>standard</b> view via HTML tag.</p>
</standard>
<tablet>
    <p>This is a <b>tablet</b> view via HTML tag.</p>
</tablet>
<mobile>
    <p>This is a <b>mobile</b> view via HTML tag.</p>
</mobile>
Если посетитель заходит на сайт с мобильного — убирается контент тегов standard и tablet. Если с компьютера — то tablet и mobile. Таким образом, вы легко можете организовать мобильную версию сайта.

Как и во втором типе, при таком вызове сначала будут распарсены все теги MODX внутри блоков, что не очень эффективно и может вести к ошибкам логики. Проблем с кэшированием нет, потому что ненужные теги убираются при выводе юзеру.

Настройки


Все возможные опции вынесены в системные настройки. Это значит, что их можно указывать раздельно для каждого контекста.
  • disable_plugin — Выключить плагин
  • use_cookie — Запоминать тип браузера юзера.
  • tablet_is_standard — Считать планшеты компьютерами и выводить для них тег standard.
  • + разные настройки для указания переменных и тегов версий


Помимо автоопределения, можно и напрямую указывать требуемую версию через url.

Исходный код в репозитории на GitHub.
Саму библиотеку Mobile Detect в директории vendor можно обновлять через Composer.

Посмотреть в работе можно на демо-сайте.

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[2.1.0-pl]

Added

  • Service API: resolveDevice(), getDeviceType(), isMobile(), isTablet(), isDesktop().
  • Fenom modifier |mobiledetect for conditional output ({if 'mobile' | mobiledetect}).
  • Example chunk tplMobileDetectSwitch with links to force desktop, tablet, mobile or auto-detect mode.

Changed

  • Updated mobiledetect/mobiledetectlib to 4.11.x (Detection\MobileDetect).
  • Explicit MODX Revolution 2.8+ and MODX 3.x support; transport build uses PSR-4 bootstrap for modPackageBuilder on MODX 3.
  • Fixed Fenom block functions ({mobile}, {phone}, {tablet}, {desktop}, {standard}) returning empty string instead of implicit null.
  • Fixed repeated Fenom registration on pdoToolsOnFenomInit (memory exhaustion on large Fenom templates).
  • Fenom init guard uses getTag('mobile') instead of getModifier('mobiledetect'): pdoTools autoloads unknown modifiers as snippets, so the old check skipped block registration.
  • Plugin is packaged as non-static (static = 0): a static plugin with a media source caused memory exhaustion while Fenom was still initializing.
  • Wrapped mobiledetectPluginService() in function_exists() so the plugin can run on both pdoToolsOnFenomInit and OnWebPagePrerender in one request.
  • Skip cookie writes in CLI and after headers are sent (canPersistCookie()).
  • Fixed potential infinite recursion in parseDocument() when saved cookie mode equals the current pass.

Fixed

  • System setting md_disable_plugin default aligned with transport settings: plugin is enabled by default (false).
  • md_tablet_is_standard now remaps tablet → standard for snippet, Fenom blocks/modifier and service API (resolveDevice, isDesktop, isTablet), not only HTML tags.

Breaking Changes

  • Requires PHP 8.2+ (mobiledetectlib 4.11.x).
  • Internal detector class changed from \Mobile_Detect to Detection\MobileDetect. Custom code that called getDetector() and relied on the legacy class must update imports and API usage.

Dependencies

  • mobiledetect/mobiledetectlib ^4.11
  • psr/simple-cache ^1.0 || ^2.0 || ^3.0

[2.0.2-pl]

Added

  • Fenom blocks {mobile}{/mobile}, {desktop}{/desktop}, {standard}{/standard}, {phone}{/phone} and {tablet}{/tablet}.

[2.0.1-pl]

Changed

  • Mobile Detect library updated to 2.8.34.

[2.0.0-pl]

Added

  • Snippet MobileDetect for conditional output in templates.

Changed

  • Mobile Detect included via Composer.
  • Mobile Detect core updated to 2.8.28.
  • Test template is no longer installed by default.

[1.0.1-pl]

Changed

  • Updated Mobile-Detect core.

[1.0.0-beta]

Added

  • Initial release: HTML tag filtering (,, `) onOnWebPagePrerender`, cookie-based mode persistence, force mode via GET parameter.

Последние обсуждения в сообществе MODX.pro