# InSales Frontend & Template Documentation для Context7.com ## Общая информация InSales - российская платформа электронной коммерции с мощной системой шаблонизации на основе Liquid и JavaScript API. **Шаблонизатор:** Liquid (форк Shopify Liquid) **Frontend API:** Common.js v2 **Структура тем:** Liquid файлы + CSS/JS/Assets **Документация:** liquidhub.ru --- ## 🎨 LIQUID ШАБЛОНИЗАТОР ### Структура файлов темы ``` root/ ├── config/ ├── media/ # CSS, JS, изображения, SVG ├── snippets/ # Переиспользуемые куски кода └── templates/ # Основные шаблоны страниц ``` ### Основные шаблоны **Layouts:** - `layouts.layout.liquid` - основной лэйаут - `layouts.checkout.liquid` - лэйаут оформления заказа **Страницы:** - `index.liquid` - главная страница - `collection.liquid` - категория товаров - `product.liquid` - страница товара - `cart.liquid` - корзина - `page.liquid` - статическая страница - `search.liquid` - поиск - `blog.liquid` - блог - `article.liquid` - статья блога **Кастомные шаблоны:** - `product.hits.liquid` - товары-хиты - `collection.sale.liquid` - распродажа - `page.contacts.liquid` - контакты ### Включение файлов ```liquid {% include 'header' %} {% include 'header' with "index" %} {% assign logo_text = 'Моя компания' %} {% include 'logo', use_image: false, logo_text: logo_text %} ``` ### Подключение стилей и скриптов **Склейка файлов через директивы:** ```scss // main.scss @import 'header'; @import 'footer'; @import 'slider'; ``` ```javascript // plugins.js #= require jquery.min #= require swiper.min #= require magnific-popup.min // main.js #= require cart #= require product #= require collection ``` --- ## 📋 ПЕРЕМЕННЫЕ LIQUID ### PRODUCT (Товар) **Основные свойства:** ```liquid {{ product.id }} {{ product.title }} {{ product.handle }} {{ product.permalink }} {{ product.url }} {{ product.description }} {{ product.short_description }} {{ product.available }} {{ product.price }} {{ product.old_price }} {{ product.price_min }} {{ product.price_max }} {{ product.price_varies? }} {{ product.old_price_varies? }} {{ product.unit }} {{ product.rating }} {{ product.reviews_count }} {{ product.show_variants? }} {{ product.updated_at }} ``` **Изображения:** ```liquid {{ product.first_image.original_url }} {{ product.first_image.large_url }} {{ product.first_image.medium_url }} {{ product.first_image.compact_url }} {{ product.first_image.thumb_url }} {{ product.first_image.small_url }} {{ product.first_image.title }} {{ product.first_image.file_name }} {% for image in product.images %} {{ image.title }} {% endfor %} ``` **Варианты товара:** ```liquid {% for variant in product.variants %} {% endfor %} {{ variant.id }} {{ variant.title }} {{ variant.price }} {{ variant.old_price }} {{ variant.available }} {{ variant.quantity }} {{ variant.sku }} {{ variant.barcode }} {{ variant.weight }} {{ variant.first_image }} ``` **Свойства и характеристики:** ```liquid {% for option_name in product.options %}

{{ option_name.title }}

{% for option_value in option_name.values %} {{ option_value.title }} {% endfor %} {% endfor %} {% for property in product.properties %}
{{ property.name }}
{% for characteristic in property.characteristics %}
{{ characteristic.name }}
{% endfor %} {% endfor %} ``` **Связанные товары:** ```liquid {% for related in product.related_products %} {{ related.title }} {% endfor %} {% for similar in product.similar_products %} {{ similar.title }} {% endfor %} ``` **Отзывы:** ```liquid {% for review in product.reviews %}
{{ review.author }}
{{ review.rating }}

{{ review.content }}

{% if review.replied? %}
{{ review.manager_reply }}
{% endif %}
{% endfor %} ``` ### COLLECTION (Категория) ```liquid {{ collection.id }} {{ collection.title }} {{ collection.handle }} {{ collection.url }} {{ collection.description }} {{ collection.products_count }} {{ collection.current? }} {{ collection.level }} {% for product in collection.products %} {{ product.title }} {% endfor %} {% for subcollection in collection.subcollections %} {{ subcollection.title }} {% endfor %} {% for filter in collection.filters %} {{ filter.title }} {% endfor %} ``` ### CART (Корзина) ```liquid {{ cart.items_count }} {{ cart.total_price }} {{ cart.items_price }} {{ cart.items_weight }} {{ cart.coupon }} {{ cart.coupon_error }} {{ cart.enable_coupon? }} {% for item in cart.items %}

{{ item.title }}

{{ item.sale_price | money }} {{ item.quantity }} {{ item.total_price | money }}

{{ item.comment }}

{% endfor %} ``` ### ORDER (Заказ) ```liquid {{ order.id }} {{ order.number }} {{ order.key }} {{ order.status }} {{ order.total_price }} {{ order.items_price }} {{ order.delivery_price }} {{ order.delivery_title }} {{ order.payment_title }} {{ order.comment }} {{ order.creation_date }} {{ order.delivery_date }} {{ order.paid? }} {% for item in order.items %} {{ item.title }} - {{ item.quantity }} шт. {% endfor %} {{ order.shipping_address.full_locality_name }} {{ order.shipping_address.address }} ``` ### CLIENT (Клиент) ```liquid {% if client %} {{ client.name }} {{ client.email }} {{ client.phone }} {{ client.bonus_points }} {{ client.group_discount }} {{ client.registered }} {% endif %} ``` ### ACCOUNT (Аккаунт/Магазин) ```liquid {{ account.title }} {{ account.email }} {{ account.phone }} {{ account.url }} {{ account.currency_code }} {{ account.reviews_enabled? }} {{ account.enable_clients? }} ``` ### BLOG & ARTICLE (Блог и статьи) ```liquid {{ blog.title }} {{ blog.handle }} {{ blog.url }} {% for article in blog.articles %}

{{ article.title }}

{{ article.author }}

{{ article.preview }}
Читать далее
{% endfor %} {{ article.content }} {{ article.image.original_url }} ``` ### SEARCH (Поиск) ```liquid {% if search.performed? %}

По запросу "{{ search.query }}" найдено:

{% for result in search.results %} {{ result.title }} {% endfor %} {% endif %} ``` ### PAGINATION (Пагинация) ```liquid {{ paginate.current_page }} {{ paginate.pages }} {{ paginate.items }} {% if paginate.previous %} Предыдущая {% endif %} {% for part in paginate.parts %} {% if part.is_link %} {{ part.title }} {% else %} {{ part.title }} {% endif %} {% endfor %} {% if paginate.next %} Следующая {% endif %} ``` ### HELPERS (Вспомогательные) ```liquid {{ forloop.index }} {{ forloop.index0 }} {{ forloop.rindex }} {{ forloop.first }} {{ forloop.last }} {{ forloop.length }} {{ images }} ``` --- ## 🔧 ФИЛЬТРЫ LIQUID ### Фильтры для массивов ```liquid {{ array | size }} {{ array | first }} {{ array | last }} {{ array | reverse }} {{ array | sort }} {{ array | uniq }} {{ array | join: ', ' }} {{ array | map: 'title' }} {{ array | where: 'available', true }} {{ array1 | concat: array2 }} ``` ### Математические фильтры ```liquid {{ price | plus: 100 }} {{ price | minus: 50 }} {{ price | times: 2 }} {{ price | divided_by: 3 }} {{ price | modulo: 10 }} {{ price | round }} {{ price | round: 2 }} {{ string_number | to_integer }} ``` ### Строковые фильтры ```liquid {{ text | append: ' suffix' }} {{ text | prepend: 'prefix ' }} {{ text | capitalize }} {{ text | upcase }} {{ text | downcase }} {{ text | escape }} {{ text | strip_html }} {{ text | newline_to_br }} {{ text | truncate: 100 }} {{ text | truncatewords: 10 }} {{ text | replace: 'old', 'new' }} {{ text | remove: 'word' }} {{ text | remove_first: 'word' }} {{ text | lstrip }} {{ text | strip_newlines }} {{ text | url_encode }} {{ text | url_decode }} {{ text | md5 }} ``` ### Фильтры для ссылок ```liquid {{ 'style.css' | asset_url }} {{ 'logo.png' | asset_url_if_exists }} {{ file | file_url }} {{ url | add_param: 'key', 'value' }} {{ path | locale_url }} ``` ### Фильтры для денег ```liquid {{ price | money }} ``` ### Фильтры для дат ```liquid {{ date | date: '%d.%m.%Y' }} {{ date | date: '%d %B %Y' }} ``` ### Дополнительные фильтры ```liquid {{ value | default: 'fallback' }} {{ object | json }} {{ object | custom_json }} {{ color | dark? }} {{ color | change_lightness: 20 }} ``` ### Фильтры для изображений ```liquid {{ image | image_url: '300x300' }} {{ image | webp_picture_tag }} ``` ### HTML фильтры ```liquid {{ options | select_option }} {{ url, text | link_to }} ``` --- ## 🔄 ОПЕРАТОРЫ И КОНСТРУКЦИИ ### Условные конструкции ```liquid {% if condition %} {% elsif another_condition %} {% else %} {% endif %} {% unless condition %} {% endunless %} {% case variable %} {% when 'value1' %} {% when 'value2' %} {% else %} {% endcase %} ``` ### Логические операторы ```liquid {% if price > 1000 %} {% if price < 500 %} {% if price >= 1000 %} {% if price <= 500 %} {% if price == 1000 %} {% if price != 1000 %} {% if product.available and price > 0 %} {% if product.available or price == 0 %} {% if title contains 'слово' %} ``` ### Циклы ```liquid {% for product in collection.products %} {{ product.title }} {% if forloop.first %} {% endif %} {% if forloop.last %} {% endif %} {% endfor %} {% for product in collection.products limit: 5 %} {{ product.title }} {% endfor %} {% for product in collection.products offset: 2 %} {{ product.title }} {% endfor %} {% for product in collection.products %} {% if product.price > 10000 %} {% break %} {% endif %} {{ product.title }} {% endfor %} {% for product in collection.products %} {% unless product.available %} {% continue %} {% endunless %} {{ product.title }} {% endfor %} {% for item in cart.items %} {{ item.title }} {% endfor %} ``` ### Специальные теги ```liquid {% capture variable_name %} Любой контент {{ product.title }} {% endcapture %} {% cache 'cache_key', expires_in: 3600 %} {% endcache %} {% help 'product' %} ``` --- ## ⚡ COMMON.JS V2 API ### Подключение В `settings_data.json`: ```json { "common_js_version": "v2" } ``` ### Основные модули **EventBus** - система событий **Cart** - работа с корзиной **Products** - работа с товарами **AjaxSearch** - живой поиск **Compare** - сравнение товаров **Template** - шаблонизация **ajaxAPI** - AJAX запросы **Shop** - данные магазина ### Работа с товарами ```javascript // Получение данных товара $.post('/products_by_id/123.json') .done(function(product) { console.log(product); }); // Обновление информации о варианте Products.updateProduct(productData); // События товара EventBus.subscribe('product:updated', function(product) { // Обработка обновления товара }); ``` ### Работа с корзиной ```javascript // Добавление в корзину Cart.addItem({ variant_id: 123, quantity: 1, comment: 'Комментарий' }); // Обновление количества Cart.updateItem(itemId, quantity); // Удаление из корзины Cart.removeItem(itemId); // События корзины EventBus.subscribe('cart:add', function(item) { // Товар добавлен в корзину }); EventBus.subscribe('cart:update', function(cart) { // Корзина обновлена }); ``` ### Живой поиск ```javascript // Инициализация поиска AjaxSearch.init({ selector: '#search-input', resultsContainer: '#search-results' }); // Кастомная обработка результатов AjaxSearch.onResults = function(results) { // Обработка результатов поиска }; ``` ### Сравнение товаров ```javascript // Добавление в сравнение Compare.addProduct(productId); // Удаление из сравнения Compare.removeProduct(productId); // Получение списка сравнения var compareList = Compare.getList(); ``` ### Избранное ```javascript // Добавление в избранное (кастомная реализация) function addToFavorites(productId) { var favorites = JSON.parse(localStorage.getItem('favorites') || '[]'); if (favorites.indexOf(productId) === -1) { favorites.push(productId); localStorage.setItem('favorites', JSON.stringify(favorites)); } } ``` ### Lodash шаблоны ```javascript // Создание шаблона var template = _.template('

<%= title %>

'); // Рендер с данными var html = template({ title: 'Заголовок' }); // В InSales ``` --- ## 📡 AJAX API ENDPOINTS ### Товары ```javascript // Получение товара по ID GET /products_by_id/{id}.json // Поиск товаров GET /search.json?q={query} // Похожие товары GET /products/{id}/related.json // Товары категории GET /collection/{handle}.json ``` ### Корзина ```javascript // Добавление в корзину POST /cart_items.json { "variant_id": 123, "quantity": 1, "comment": "Комментарий" } // Обновление корзины PUT /cart_items/{id}.json { "quantity": 2 } // Удаление из корзины DELETE /cart_items/{id}.json // Получение корзины GET /cart_items.json ``` ### Клиенты ```javascript // Регистрация POST /client_account.json // Вход POST /client_account/session.json // Получение данных клиента GET /client_account.json ``` ### Отзывы ```javascript // Добавление отзыва POST /products/{id}/reviews.json { "review": { "author": "Имя", "email": "email@example.com", "content": "Текст отзыва", "rating": 5 } } ``` --- ## 🛍️ ПРИМЕРЫ ФОРМ ### Форма добавления в корзину ```liquid
{% if product.show_variants? %} {% else %} {% endif %}
``` ### Форма быстрого заказа ```liquid
``` ### Форма отзыва ```liquid
{% for i in (1..5) %} {% endfor %}
``` --- ## 🎯 ПРАКТИЧЕСКИЕ ПРИМЕРЫ ### Карточка товара с вариантами ```liquid
{% for image in product.images %} {{ product.title }} {% endfor %}

{{ product.title }}

{% if product.old_price %} {{ product.old_price | money }} {% endif %} {{ product.price | money }}
{% if product.available %} В наличии {% else %} Нет в наличии {% endif %}
{% if product.sku %}
Артикул: {{ product.variants.first.sku }}
{% endif %} {{ product.description }}
``` ### Корзина с AJAX обновлением ```liquid
{% for item in cart.items %}
{{ item.title }}

{{ item.title }}

{{ item.sale_price | money }} {{ item.total_price | money }}
{% endfor %}
Итого: {{ cart.total_price | money }}
Оформить заказ
``` ### Фильтры в категории ```liquid
{% for filter in collection.filters %}

{{ filter.title }}

{% case filter.type %} {% when 'price' %} {% when 'property' %} {% for characteristic in filter.characteristics %} {% endfor %} {% when 'option' %} {% for option_value in filter.option_values %} {% endfor %} {% endcase %}
{% endfor %}
``` ### Поиск с автодополнением ```liquid
``` --- ## 🔧 SETUP.JSON - Конфигурация темы ### Структура setup.json ```json { "categories": { "sale": "Распродажа", "new": "Новинки" }, "collections": { "featured": { "title": "Рекомендуемые товары", "products": ["product-1", "product-2"] } }, "products": { "product-1": { "title": "Товар 1", "price": "1000.0", "variants": { "variant-1": { "title": "Размер M", "price": "1000.0" } } } }, "pages": { "delivery": "Доставка", "payment": { "title": "Оплата", "content": "Информация об оплате" } }, "blogs": { "news": { "title": "Новости", "articles": { "article-1": { "title": "Новая коллекция", "content": "Описание коллекции", "author": "Администратор" } } } }, "menus": { "main-menu": "Главное меню", "footer-menu": "Меню в подвале" }, "menu_items": { "main-menu": { "Главная": "/", "Каталог": "/collections/all", "О нас": "/pages/about" } }, "properties": { "brand": { "title": "Бренд", "characteristics": { "nike": "Nike", "adidas": "Adidas" } } } } ``` --- ## 📱 АДАПТИВНОСТЬ И МОБИЛЬНЫЕ УСТРОЙСТВА ### Responsive изображения ```liquid {{ image.title }} {{ image | webp_picture_tag }} ``` ### Мобильное меню ```liquid ``` --- ## 🚀 ОПТИМИЗАЦИЯ И ПРОИЗВОДИТЕЛЬНОСТЬ ### Ленивая загрузка изображений ```liquid {{ image.title }} ``` ### Кеширование ```liquid {% cache 'product-' | append: product.id, expires_in: 3600 %} {{ product.title }} {{ product.description }} {% endcache %} ``` ### Минификация и сжатие ```scss // Используйте SCSS для оптимизации $breakpoints: ( mobile: 480px, tablet: 768px, desktop: 1024px ); @mixin respond-to($breakpoint) { @media (min-width: map-get($breakpoints, $breakpoint)) { @content; } } ``` --- ## 🔒 БЕЗОПАСНОСТЬ ### Экранирование данных ```liquid {{ comment.content | escape }} {{ search.query | escape }} {{ user_content | strip_html }} ``` ### CSRF защита ```liquid
{{ form.csrf_token }}
``` --- ## 📊 АНАЛИТИКА И МЕТРИКИ ### Google Analytics ```liquid {% if account.google_analytics_id %} {% endif %} ``` ### Отслеживание событий ```javascript // Отслеживание добавления в корзину EventBus.subscribe('cart:add', function(item) { gtag('event', 'add_to_cart', { 'currency': 'RUB', 'value': item.sale_price, 'items': [{ 'item_id': item.variant.sku, 'item_name': item.title, 'quantity': item.quantity }] }); }); ``` --- ## 🎨 CSS ФРЕЙМВОРКИ И БИБЛИОТЕКИ ### Популярные библиотеки для InSales **CSS:** - Bootstrap 5 - Tailwind CSS - Bulma **JavaScript:** - Swiper.js (слайдеры) - Fancybox (галереи) - Select2 (селекты) - Magnific Popup (попапы) **Иконки:** - Font Awesome - Feather Icons - Heroicons ### Подключение через CDN ```liquid ``` --- ## 🛠️ ИНСТРУМЕНТЫ РАЗРАБОТКИ ### InSales Uploader ```bash # Установка npm install -g insales-uploader # Инициализация insales theme:init # Загрузка темы insales theme:download # Выгрузка изменений insales theme:upload # Просмотр логов insales theme:watch ``` ### Структура проекта ``` project/ ├── src/ │ ├── scss/ │ ├── js/ │ └── images/ ├── config/ ├── media/ ├── snippets/ ├── templates/ ├── gulpfile.js ├── package.json └── .insalesrc ``` --- ## 🔍 ОТЛАДКА И ТЕСТИРОВАНИЕ ### Режим разработки ```liquid {% if account.subdomain == 'test-shop' %} {% endif %} ``` ### Полезные хелперы ```liquid {{ product | json }} {% if product.custom_field %} {{ product.custom_field }} {% endif %} {% comment %} Текущая страница: {{ template }} ID товара: {{ product.id }} Доступность: {{ product.available }} {% endcomment %} ``` --- ## 📚 ДОПОЛНИТЕЛЬНЫЕ РЕСУРСЫ ### Официальная документация - **LiquidHub:** https://liquidhub.ru/ - **InSales API:** https://api.insales.ru/ - **GitHub репозитории:** https://github.com/liquid-hub/ ### Полезные ссылки - **Документация Liquid:** https://liquidhub.ru/collection/shpargalka-liquid - **Фильтры:** https://liquidhub.ru/collection/filtry-liquid - **Операторы:** https://liquidhub.ru/collection/operatory_i_konstruktsii - **Common.js v2:** https://docs.liquidhub.ru/common.v2.js/ ### Сообщество - **Telegram:** @insalesthemes - **GitHub:** liquid-hub organization --- ## ⚠️ ВАЖНЫЕ ЗАМЕЧАНИЯ 1. **Версия Common.js:** Убедитесь что используете v2 для современных возможностей 2. **Кеширование:** Используйте кеш для тяжелых операций 3. **Производительность:** Оптимизируйте изображения и минифицируйте код 4. **Безопасность:** Всегда экранируйте пользовательские данные 5. **Адаптивность:** Тестируйте на всех устройствах 6. **SEO:** Используйте правильные meta теги и структурированные данные --- *Этот документ содержит полную информацию для разработки фронтенда интернет-магазинов на платформе InSales. Используйте его как справочник при работе с Liquid шаблонизатором и JavaScript API.*