R
Interview Deckreact · next.js · senior/staff
0·0·122
System Design

Shopify Liquid — Template Engine

Linguagem de template dos temas Shopify. Sintaxe simples, lógica restrita por segurança.

Liquid é a linguagem de template criada pelo Shopify e usada em todos os temas tradicionais (Dawn, Debut, etc.). Sintaxe: `{{ output }}` para imprimir variáveis, `{% logic %}` para tags. Object-oriented com objects (product, cart, customer), filters (money, json, default), e tags (if, for, assign, section). Renderiza no servidor da Shopify — você não controla onde nem como.

Problema
Não dá pra rodar JavaScript arbitrário em Liquid (não há `eval`, não há acesso a APIs externas, fetch é limitado). Loops têm limite de 50 iterações em algumas tags. Performance ruim em listas grandes. Difícil testar localmente sem CLI/ngrok.
Solução
Para customização simples (header, footer, página de produto): Liquid é suficiente e rápido de desenvolver. Para lógica complexa: combinar Liquid (estrutura) + JS no cliente (interatividade) + Section Rendering API (re-renderizar sections via fetch). Para algo realmente customizado: migrar para Hydrogen.
Tip
Section Rendering API é o "secret weapon" do Liquid: você faz `fetch("/products/x?sections=cart-drawer")` e o Shopify retorna o HTML rendezido daquela section. Permite atualizações dinâmicas (ex: cart drawer) sem SPA, mantendo o tema Liquid.
{% comment %} sections/product-info.liquid {% endcomment %}
{% comment %} Schema configurável no theme editor {% endcomment %}
{% schema %}
{
  "name": "Product Info",
  "settings": [
    { "type": "checkbox", "id": "show_vendor", "label": "Mostrar marca", "default": true },
    { "type": "select", "id": "heading_size", "label": "Tamanho do título",
      "options": [
        { "value": "h2", "label": "Médio" },
        { "value": "h1", "label": "Grande" }
      ], "default": "h1" }
  ],
  "blocks": [
    { "type": "title", "name": "Título", "limit": 1 },
    { "type": "price", "name": "Preço", "limit": 1 }
  ]
}
{% endschema %}

{%- assign product = product -%}

<div class="product-info" itemscope itemtype="https://schema.org/Product">
  {%- for block in section.blocks -%}
    {%- case block.type -%}
      {%- when 'title' -%}
        {% if section.settings.show_vendor %}
          <p class="vendor">{{ product.vendor | escape }}</p>
        {% endif %}
        <{{ section.settings.heading_size }} itemprop="name">
          {{ product.title | escape }}
        </{{ section.settings.heading_size }}>

      {%- when 'price' -%}
        <p class="price" itemprop="price" content="{{ product.price | money_without_currency }}">
          {{ product.price | money }}
          {%- if product.compare_at_price > product.price -%}
            <s>{{ product.compare_at_price | money }}</s>
          {%- endif -%}
        </p>
    {%- endcase -%}
  {%- endfor -%}
</div>

{%- comment -%} Section Rendering API: fetch GET /products/{handle}?sections=product-info {%- endcomment -%}
Q.O que são Sections e Blocks em Liquid?
A.Sections: blocos modulares reutilizáveis (hero, product-grid, testimonials). Configuráveis pelo merchant no theme editor via schema JSON. Blocks: itens dentro de sections, repetíveis e ordenáveis. Ex: section "image-with-text" pode ter blocks "heading", "text", "button". Tudo declarativo, zero deploy para mudanças visuais — merchant faz no admin.
Q.Como debugar Liquid?
A.Use `{{ object | json }}` para serializar e ver o conteúdo. Liquid não tem stack trace — erros silenciam. Shopify CLI tem hot reload local com `shopify theme dev`. Use comment tags `{% comment %} ... {% endcomment %}` para isolar problemas. Para perfil: aba Network do DevTools (templates renderizam server-side).
Q.Quando usar Liquid Online Store 2.0 vs Hydrogen?
A.OS 2.0 (Liquid moderno com Sections Everywhere, App Blocks, Metaobjects): merchants mantêm controle no theme editor, time pequeno, prazo curto, customização média. Hydrogen: time React experiente, performance crítica, controle total do front, marca premium com identidade visual forte. OS 2.0 é o caminho default; Hydrogen quando OS 2.0 não basta.
113/122← →