基于Shopify官方教程,如何在{% schema %}区块添加动态内容?
Great question! Let’s break down how to add dynamic functionality to your Shopify theme’s {% schema %} block—keep in mind that the schema itself is static JSON, so we’ll leverage Shopify’s built-in features and pair it with Liquid logic outside the schema to achieve dynamic behavior.
1. Dynamic Selection Options (Sync with Store Data)
Shopify has built-in field types that automatically pull dynamic data from your store, like collections, products, pages, or blog posts. Use these to let merchants select from existing store assets directly in the theme editor.
Example: Add a dynamic collection picker
{% schema %} { "name": "Featured Collection Section", "class": "index-section", "settings": [ { "type": "collection", "id": "featured_collection", "label": "Choose a collection to feature", "dynamic_source": "collections" } ], "presets": [ { "name": "Featured Collection", "category": "Collections" } ] } {% endschema %}
This will render a dropdown in the theme editor that automatically updates whenever you add/remove collections in your store—no manual updates to the schema needed.
2. Dynamic Default Values
While you can’t set dynamic defaults directly in the JSON schema, you can use Liquid logic in your template to override the static default with dynamic content.
Example: Default to the store’s most recent collection
{% schema %} { "name": "Latest Collection Section", "settings": [ { "type": "collection", "id": "target_collection", "label": "Select a collection", "default": "frontpage" } ] } {% endschema %} {% comment %} Override default with the newest collection if no selection is made {% endcomment %} {% assign display_collection = section.settings.target_collection | default: collections.last %} <div class="collection-section"> <h2>{{ display_collection.title }}</h2> {% for product in display_collection.products limit: 4 %} <!-- Product markup here --> {% endfor %} </div>
3. Dynamic Text/Content with Liquid Parsing
If you want merchants to input text that includes dynamic values (like {{ shop.name }} or {{ customer.name }}), use the liquify filter to parse Liquid tags from the schema’s text input.
Example: Dynamic text block
{% schema %} { "name": "Dynamic Text Block", "settings": [ { "type": "textarea", "id": "custom_text", "label": "Enter text (supports Liquid tags like {{ shop.name }})", "default": "Welcome to {{ shop.name }}! We have {{ collections.all.size }} collections for you." } ] } {% endschema %} <div class="dynamic-text-content"> {{ section.settings.custom_text | liquify }} </div>
The liquify filter will render the dynamic values in real-time, so the text updates automatically when your store’s data changes.
Key Note
Remember: The {% schema %} block itself must be valid static JSON—you can’t insert Liquid directly inside it. All dynamic logic happens in the template code that references the schema’s settings, or via Shopify’s native dynamic field types.
内容的提问来源于stack exchange,提问作者Hussam Kurd

