办公效率

Shopify主题开发与性能优化

用 Liquid 和 JSON 创建商家可配置的区块、商品页及购物车,并优化加载速度。

# Shopify 主题开发

## 概述

使用 Liquid 模板、JSON 模板、可供商家自定义布局的区段和区块,以及用于应用集成的主题应用扩展,构建和自定义 Shopify 主题。本技能涵盖 Shopify 主题架构(Online Store 2.0)、Shopify CLI 开发工作流、使用延迟加载和关键 CSS 进行性能优化,以及构建可供商家通过主题编辑器配置的灵活区段的模式。

## 何时使用本技能

- 从零开始构建 Shopify 主题或 fork Dawn 时
- 为主题编辑器创建自定义区段和区块时
- 使用 Liquid 实现产品页面、产品系列网格或购物车功能时
- 针对 Core Web Vitals 和速度优化 Shopify 主题时
- 构建主题应用扩展以将应用内容注入主题时

## 核心指令

1. **使用 Shopify CLI 设置开发环境**

   ```bash
   # Install Shopify CLI
   npm install -g @shopify/cli @shopify/theme

   # Initialize a new theme (or clone Dawn)
   shopify theme init my-theme

   # Start development server with hot reload
   shopify theme dev --store=your-store.myshopify.com
   ```

   主题目录结构(Online Store 2.0):
   ```
   my-theme/
   ├── assets/          # CSS, JS, images
   ├── config/          # settings_schema.json, settings_data.json
   ├── layout/          # theme.liquid (main layout)
   ├── locales/         # Translation files
   ├── sections/        # Sections (reusable, merchant-configurable)
   ├── snippets/        # Partials (reusable Liquid fragments)
   └── templates/       # JSON templates referencing sections
       ├── product.json
       ├── collection.json
       └── index.json
   ```

2. **创建包含区段的 JSON 模板**

   ```json
   // templates/product.json
   {
     "sections": {
       "main": {
         "type": "main-product",
         "settings": {}
       },
       "recommendations": {
         "type": "product-recommendations",
         "settings": {
           "heading": "You may also like",
           "products_to_show": 4
         }
       },
       "reviews": {
         "type": "product-reviews",
         "settings": {}
       }
     },
     "order": ["main", "recommendations", "reviews"]
   }
   ```

3. **使用区块构建可自定义的产品区段**

   ```liquid
   {% comment %}
     sections/main-product.liquid
   {% endcomment %}

   <section class="product-section" data-section-id="{{ section.id }}">

         {% for media in product.media %}
           {% case media.media_type %}
             {% when 'image' %}

                 {{ media | image_url: width: 800 | image_tag:
                   loading: 'lazy',
                   widths: '200,400,600,800,1000',
                   sizes: '(min-width: 768px) 50vw, 100vw',
                   class: 'product-image'
                 }}

             {% when 'video' %}

                 {{ media | video_tag: autoplay: false, controls: true }}

           {% endcase %}
         {% endfor %}

         {% for block in section.blocks %}
           {% case block.type %}
             {% when 'title' %}
               <h1 class="product-title" {{ block.shopify_attributes }}>
                 {{ product.title }}
               </h1>

             {% when 'price' %}

                 {% if product.compare_at_price > product.price %}
                   <s class="price-compare">{{ product.compare_at_price | money }}</s>
                 {% endif %}
                 {{ product.price | money }}
                 {% if product.compare_at_price > product.price %}
                   Sale
                 {% endif %}

             {% when 'variant_picker' %}

                 {% for option in product.options_with_values %}
                   <fieldset class="option-group">
                     <legend>{{ option.name }}</legend>
                     {% for value in option.values %}
                       <label class="option-label">
                         <input
                           type="radio"
                           name="{{ option.name }}"
                           value="{{ value }}"
                           {% if option.selected_value == value %}checked{% endif %}
                         >
                         {{ value }}
                       </label>
                     {% endfor %}
                   </fieldset>
                 {% endfor %}

             {% when 'buy_buttons' %}

                 {% form 'product', product %}
                   <input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}">

                     <label for="quantity">Quantity</label>
                     <input type="number" id="quantity" name="quantity" value="1" min="1">

                   <button
                     type="submit"
                     class="btn btn-primary add-to-cart"
                     {% unless product.selected_or_first_available_variant.available %}disabled{% endunless %}
                   >
                     {% if product.selected_or_first_available_variant.available %}
                       Add to cart — {{ product.selected_or_first_available_variant.price | money }}
                     {% else %}
                       Sold out
                     {% endif %}
                   </button>
                 {% endform %}

             {% when 'description' %}

                 {{ product.description }}

             {% when 'custom_text' %}

                 {{ block.settings.text }}

           {% endcase %}
         {% endfor %}

   </section>

   {% schema %}
   {
     "name": "Product Page",
     "tag": "section",
     "class": "section-product",
     "blocks": [
       {
         "type": "title",
         "name": "Title",
         "limit": 1
       },
       {
         "type": "price",
         "name": "Price",
         "limit": 1
       },
       {
         "type": "variant_picker",
         "name": "Variant Picker",
         "limit": 1
       },
       {
         "type": "buy_buttons",
         "name": "Buy Buttons",
         "limit": 1
       },
       {
         "type": "description",
         "name": "Description",
         "limit": 1
       },
       {
         "type": "custom_text",
         "name": "Custom Text",
         "settings": [
           {
             "type": "richtext",
             "id": "text",
             "label": "Text"
           }
         ]
       }
     ],
     "presets": [
       {
         "name": "Product Page",
         "blocks": [
           { "type": "title" },
           { "type": "price" },
           { "type": "variant_picker" },
           { "type": "buy_buttons" },
           { "type": "description" }
         ]
       }
     ]
   }
   {% endschema %}
   ```

4. **使用 Cart API 实现 AJAX 购物车**

   ```javascript
   // assets/cart.js
   class CartManager {
     async addItem(variantId, quantity = 1) {
       const response = await fetch('/cart/add.js', {
         method: 'POST',
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify({
           items: [{ id: variantId, quantity }],
         }),
       });

       if (!response.ok) {
         const error = await response.json();
         throw new Error(error.description || 'Could not add to cart');
       }

       const data = await response.json();
       this.updateCartUI();
       return data;
     }

     async updateQuantity(lineKey, quantity) {
       const response = await fetch('/cart/change.js', {
         method: 'POST',
         headers: { 'Content-Type': 'application/json' },
         body: JSON.stringify({ id: lineKey, quantity }),
       });

       const cart = await response.json();
       this.updateCartUI(cart);
       return cart;
     }

     async getCart() {
       const response = await fetch('/cart.js');
       return response.json();
     }

     async updateCartUI(cart) {
       cart = cart || await this.getCart();

       // Update cart count badge
       const badge = document.querySelector('[data-cart-count]');
       if (badge) badge.textContent = cart.item_count;

       // Update cart drawer if open
       const drawer = document.querySelector('cart-drawer');
       if (drawer) drawer.render(cart);
     }
   }

   window.cart = new CartManager();
   ```

5. **优化性能**

   ```liquid
   {% comment %}
     layout/theme.liquid — Critical performance optimizations
   {% endcomment %}
   <!doctype html>
   <html lang="{{ request.locale.iso_code }}">
   <head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">

     <!-- Preconnect to Shopify CDN -->
     <link rel="preconnect" href="https://cdn.shopify.com" crossorigin>
     <link rel="preconnect" href="https://fonts.shopifycdn.com" crossorigin>

     <!-- Preload critical assets -->
     {% if template.name == 'product' %}
       {% assign hero_image = product.featured_image %}
       {% if hero_image %}
         <link
           rel="preload"
           as="image"
           href="{{ hero_image | image_url: width: 800 }}"
           imagesrcset="{{ hero_image | image_url: width: 400 }} 400w,
                        {{ hero_image | image_url: width: 800 }} 800w"
           imagesizes="(min-width: 768px) 50vw, 100vw"
         >
       {% endif %}
     {% endif %}

     <!-- Inline critical CSS -->
     <style>
       {{ 'critical.css' | asset_url | stylesheet_tag | split: '<link' | first }}
     </style>

     <!-- Defer non-critical CSS -->
     <link rel="stylesheet" href="{{ 'theme.css' | asset_url }}" media="print" onload="this.media='all'">
     <noscript><link rel="stylesheet" href="{{ 'theme.css' | asset_url }}"></noscript>

     {{ content_for_header }}
   </head>
   <body>
     {{ content_for_layout }}

     <!-- Defer JavaScript -->
     <script src="{{ 'theme.js' | asset_url }}" defer></script>
   </body>
   </html>
   ```

6. **创建主题应用扩展**

   ```bash
   # Generate a theme app extension block
   shopify app generate extension --type theme_app_extension --name my-app-block
   ```

   ```liquid
   {% comment %}
     extensions/my-app-block/blocks/product-badge.liquid
   {% endcomment %}

     {% if block.settings.badge_text != blank %}

         {{ block.settings.badge_text }}

     {% endif %}

   {% schema %}
   {
     "name": "Product Badge",
     "target": "section",
     "settings": [
       {
         "type": "text",
         "id": "badge_text",
         "label": "Badge text",
         "default": "New"
       },
       {
         "type": "color",
         "id": "badge_color",
         "label": "Badge color",
         "default": "#FF0000"
       },
       {
         "type": "color",
         "id": "text_color",
         "label": "Text color",
         "default": "#FFFFFF"
       }
     ]
   }
   {% endschema %}
   ```

## 示例

### 带延迟加载图片的产品系列网格

```liquid
{% comment %} sections/collection-grid.liquid {% endcomment %}
<section class="collection-grid">
  <h1>{{ collection.title }}</h1>

    {% paginate collection.products by 24 %}
      {% for product in collection.products %}

          <a href="{{ product.url }}">
            {% if product.featured_image %}
              {{ product.featured_image | image_url: width: 400 | image_tag:
                loading: 'lazy',
                widths: '200,300,400',
                sizes: '(min-width: 1024px) 25vw, (min-width: 768px) 33vw, 50vw',
                class: 'product-card-image'
              }}
            {% endif %}
            <h2 class="product-card-title">{{ product.title }}</h2>
            {{ product.price | money }}
          </a>

      {% endfor %}

      {% if paginate.pages > 1 %}
        <nav class="pagination" aria-label="Pagination">
          {{ paginate | default_pagination: next: 'Next', previous: 'Previous' }}
        </nav>
      {% endif %}
    {% endpaginate %}

</section>
```

### 使用 JavaScript 切换产品变体

```javascript
// assets/variant-selector.js
class VariantSelector extends HTMLElement {
  connectedCallback() {
    this.addEventListener('change', this.onVariantChange.bind(this));
    this.productData = JSON.parse(
      this.querySelector('[type="application/json"]').textContent
    );
  }

  onVariantChange() {
    const selectedOptions = [...this.querySelectorAll('input:checked')].map(
      input => input.value
    );

    const variant = this.productData.variants.find(v =>
      v.options.every((opt, i) => opt === selectedOptions[i])
    );

    if (!variant) return;

    // Update URL without reload
    const url = new URL(window.location);
    url.searchParams.set('variant', variant.id);
    window.history.replaceState({}, '', url);

    // Update price display
    const priceEl = document.querySelector('.price-current');
    if (priceEl) {
      priceEl.textContent = this.formatMoney(variant.price);
    }

    // Update add-to-cart button
    const addToCart = document.querySelector('.add-to-cart');
    const idInput = document.querySelector('input[name="id"]');
    if (addToCart && idInput) {
      idInput.value = variant.id;
      addToCart.disabled = !variant.available;
      addToCart.textContent = variant.available ? 'Add to cart' : 'Sold out';
    }
  }

  formatMoney(cents) {
    return '$' + (cents / 100).toFixed(2);
  }
}

customElements.define('variant-selector', VariantSelector);
```

## 最佳实践

- **使用 Online Store 2.0 JSON 模板**——商家无需编辑代码即可添加、删除区段并调整其顺序
- **使用 `image_url` 和 `image_tag` 过滤器**——它们会根据 Shopify 的 CDN 自动生成响应式 `srcset` 属性
- **始终包含 `{{ block.shopify_attributes }}`**——主题编辑器需要这个数据属性来识别和选择区块
- **延迟加载所有 JavaScript**——在 script 标签上使用 `defer` 或 `type="module"`;避免阻塞渲染的 JS
- **使用 Shopify 原生 Liquid 过滤器**——`| money`、`| image_url`、`| asset_url` 已经过优化且能处理边界情况;不要重复实现
- **提供区段预设**——预设定义商家添加区段时的默认状态;没有预设,区段就不会出现在“Add section”中
- **将每个区段的 Liquid 代码控制在 50KB 以下**——大型区段会拖慢 Liquid 渲染器;将可复用代码提取到 snippets 中
- **在 Shopify 的预发布主题上测试**——部署到正式主题前,始终在未发布的主题上预览更改

## 常见问题

| 问题 | 解决方法 |
|---------|----------|
| 区段没有出现在“Add section”菜单中 | 确保区段的 `{% schema %}` 中有 `presets` 数组;没有预设的区段只能在 JSON 模板中使用 |
| 主题编辑器显示“Error rendering section” | 检查 Liquid 语法错误;使用 `shopify theme check` 检查 Liquid 代码 |
| Shopify CDN 上的图片无法加载 | 使用 `image_url` 过滤器并显式指定 `width` 参数;旧的 `img_url` 过滤器已弃用 |
| 通过 AJAX 添加商品后购物车数量徽标没有更新 | 每次修改购物车后获取 `/cart.js` 并更新徽标;不要仅依赖 `add.js` 的响应 |
| 最大内容绘制(LCP)速度慢 | 在 `<head>` 中使用 `<link rel="preload" as="image">` 预加载首屏主图或产品图片;内联关键 CSS |
| 无法在 Liquid 中访问元字段 | 确保已在 Shopify 后台创建元字段定义;通过 `product.metafields.namespace.key` 访问 |

## 相关技能

- @product-page-design
- @ecommerce-seo
- @ecommerce-caching
- @storefront-performance
- @shopify-app-development

同类提示词

办公效率· n8n 工作流的对话模型

商品照片转棚拍广告生图指令

上传商品照片并提供说明文字,分析材质、配色和原图问题,写出保留商品外观的棚拍广告生图指令。

=你是一位专业产品摄影师和广告创意总监。分析上传的产品图片及其配文:{{ $('Telegram Trigger Received').item.json.message.caption }} 你的任务是创建一段详细的图像生成提示词,将这张产品照片转化为高端、商业级的广告视觉作品。 分析要求: 1. **产品识别**:识别产品类型、尺寸、类别、材质、配色和关键特征 2. **当前状态评估**:指出当前的光线、背景、构图和质量问题 3. **目标美学**:根据产品类别确定理想的广告风格(奢侈品、科技、食品、时尚等) 输出(严格使用 JSON 格式):
办公效率· n8n 工作流的对话模型

Veo 3营销视频分镜指令

填写视频需求、营销目标、图像描述和画幅,生成包含场景、运镜、动作、灯光与结尾的结构化制片指令。

=# Veo3 视频生成系统提示词 你是一名专业的视频提示词工程师,擅长为 Veo3 视频生成撰写细致、富有电影感的提示词。你的角色是分析用户输入,将其转化为全面的视频生成指令,以产出高质量、引人入胜的内容。 ## 输入分析 你将收到以下用户输入: - **AI Videos instructions**:视频生成的核心用户请求 - **Campaign objectives**:营销活动目标和说明 - **Images Description**:用户提供的视觉背景信息 - **Aspect Ratio**:要求的视频尺寸比例 ## 输出格式 你
可填 21 项
办公效率· n8n 工作流的对话模型

保留原品的社媒广告视觉方案

提供商品图和配文,生成保留原品外观的广告生图说明,广告文字仅从配文提取,缺项留空。

={ "system_prompt": "你是一位顶尖创意总监,专攻爆款产品广告,拥有15年以上奢侈品牌广告活动经验。将产品图片转化为商业级广告,让浏览者停下滑动并促进转化。", "instructions": { "core_rules": [ "保持原始产品100%不变——不得修改、替换或扭曲", "只提取和使用用户配文中提供的文字", "如果配文中没有相关文字,文字字段留空——绝不生成AI广告语", "专注于高端视觉强化和商业摄影技巧", "制作适合在Instagram展
办公效率· Claude Fable 5.2

用代码制作长纪录片流程

从题材调研、脚本和样帧审核开始,按章节生成三维分镜、旁白、环境声与可复现渲染。

<inputs> 向我询问: 1. 我的主题 2. 目标视频时长 3. 我是否已有脚本 如果我只给你一个主题,先研究该主题并撰写脚本。 开始制作任何内容之前,先向我展示: - 完整脚本 - 章节拆分 - 前 60 seconds 的分镜计划 - 6 张展示预期视觉方向的静帧 在我认可视觉效果之前,不要渲染完整视频。 </inputs> <story> 按照高品质 YouTube 纪录片的方式来写,不要写成 AI 科普解说。 故事必须始终向前推进。 每个部分都需要包含以下内容之一: - 一个新问题 - 一个揭示 - 一个矛盾 - 一个后果 - 一条证据
办公效率

同场景表情变化九宫格自拍

上传主角照片,可选搭档参考图或设定,并填写服装、背景或姿势偏好,生成同一布光和构图的九张变化。

# photo-booth ## 何时使用此 skill - 当用户希望根据参考图制作大头贴宫格、表情宫格、情侣自拍宫格、同步姿势组图或多种人像变体时使用。 - 当请求制作 3x3 宫格,且主体、房间、服装、构图和布光保持一致,仅表情或细微姿势发生变化时触发。 ## 必需输入 - 主要人物的主参考图。 - 可选的伴侣或角色参考图。 - 如果未提供伴侣参考图,需提供期望的伴侣设定。 - 用户指定的服装、背景、摄影时代、姿势清单或氛围。 如果缺少主参考图,请用户附上。如果伴侣设定或预期风格不明确,提出一个有针对性的问题。 ## 连续性规则 -
需参考图
办公效率· Claude Code / 动效编程

单镜头立体落地页飞越动画

提供落地页链接、品牌名、标志和两段收尾文案,可选配乐,制作卡片随镜头掠过而浮起的连续飞越短片。

<inputs> 向我索取:我的落地页链接、品牌名称和标志、由两部分组成的结尾文案(一句陈述,后接一小段斜体文字),以及一条 15 second 音轨(可选)。 </inputs> <direction> 以 60fps 对我的落地页进行 14.5 second 3D 飞越拍摄,1440x1152。页面平放在明亮的摄影棚地面上(中央为 #f9fbfb,角落为 #f2f3f6),周围有柔和宽阔的阴影,圆角为 24px。全程使用一个连续镜头,绝不切镜:镜头从首屏上方低处开始,以恒定速度沿页面向后滑行,同时朝页面上方看去;然后垂直升至正上方,将整个页面呈现为
✓