Theme Development
Build custom Liquid themes for Cartly. Understand the three-layer resolver, fork-on-write semantics, section schema, and how the code editor tracks your customizations.
Architecture
Cartly themes use a three-layer file resolver. When a file is requested — by the storefront renderer or the code editor — the platform checks layers in this order:
- DB row — a fork the merchant created by editing the file in the code editor. Stored as a JSON field on the
ThemeInstallentity. - Platform embed FS — the current version bundled with the platform binary (
backend/internal/theme/embed/). - Boilerplate FS — legacy fallback for files not yet in the embed (
backend/internal/theme/boilerplate/).
// Three-layer resolver — checked in order for every file request
//
// 1. DB row (theme_files JSONB on ThemeInstall)
// → present when the merchant has forked (edited) the file
//
// 2. Platform embed FS (backend/internal/theme/embed/)
// → the current version shipped with the platform binary
//
// 3. Boilerplate FS (backend/internal/theme/boilerplate/)
// → fallback for files not yet in embed (legacy installs)
//
// "Fork-on-write": a DB row is created only when the merchant
// explicitly saves an edit. Until then, the embed version is served
// transparently — so platform updates flow in automatically.Clarity is the canonical reference theme — it exercises the full Cartly theme API including section groups, alternate templates, wishlist, Quick-Add, faceted filtering, Customer Account on Liquid, and the {{ 'key' | t }} i18n filter across all seven supported locales. See the Clarity Theme guide for its section architecture, design tokens, and fork workflow. The theme source lives at backend/internal/theme/templates/themes/clarity/.
Fork-on-write is the key invariant: no DB row exists until the merchant explicitly saves an edit. Fresh shops carry only their page graph and design tokens in the database. Platform updates automatically reach all unforked (stock) files on the next deploy — merchants never need to manually sync boilerplate changes.
When the platform ships a new version of a section the merchant has already forked, the code editor shows an amber Upstream updated banner. The merchant can review the diff and choose to sync or keep their version.
File Types
| Path pattern | Description |
|---|---|
sections/*.liquid | Section templates. Must contain a {%- schema -%} block. Rendered by the storefront and available in the + Add panel. |
snippets/*.liquid | Reusable partials included via {% render 'snippet-name' %}. No schema block. |
layouts/*.liquid | Page wrapper layouts. layouts/theme.liquid is the default — it wraps every storefront page via {{ content_for_layout }}. |
templates/*.json | Page graph — JSON array of section keys and their settings. One file per page type (index.json, product.json, etc.). Editable with "Open in Visual Editor" from the code editor context menu. |
assets/* | CSS, JS, images. Referenced in Liquid via {{ 'theme.css' | asset_url }}. |
locales/*.json | Translation strings consumed by the {{ 'key' | t }} filter. |
config/settings_data.json | Current values for theme-level settings (colors, fonts, global toggles). |
Schema Reference
Every sections/*.liquid file must end with a {%- schema -%} block. The schema drives the Visual Editor sidebar and the + Add panel.
Required fields
| Field | Type | Description |
|---|---|---|
name | string | Display name shown in the + Add panel |
presets | array | At least one preset required — provides the default blocks and settings when the section is added via the + Add panel. Without this the section is invisible. |
Setting field types
| type | Editor widget | Value in Liquid |
|---|---|---|
text | Single-line input | string |
textarea | Multi-line input | string |
image_picker | Media selector overlay | Media URL string (use with | img_url) |
color | Color picker | hex string e.g. #6366f1 |
range | Slider (requires min / max / step) | number |
select | Dropdown (requires options array) | selected value string |
checkbox | Toggle | boolean |
url | URL input with link picker | string |
product | Product typeahead search | product UUID |
collection | Collection typeahead search | collection UUID |
Full section example
<section
class="cartly-section"
data-section-id="{{ section.id }}"
data-section-type="{{ section.type }}"
>
<div class="container">
<h2 data-cartly-edit="heading">{{ section.settings.heading }}</h2>
<p data-cartly-edit="body_text">{{ section.settings.body_text }}</p>
<div class="features-grid">
{%- for block in section.blocks -%}
{%- case block.type -%}
{%- when 'feature_item' -%}
<div class="feature-card" data-block-id="{{ block.id }}">
<h3 data-cartly-edit="title">{{ block.settings.title }}</h3>
<p data-cartly-edit="description">{{ block.settings.description }}</p>
</div>
{%- endcase -%}
{%- endfor -%}
</div>
</div>
</section>
{%- schema -%}
{
"name": "Feature Grid",
"tag": "section",
"settings": [
{
"type": "text",
"id": "heading",
"label": "Heading",
"default": "Our Features"
},
{
"type": "textarea",
"id": "body_text",
"label": "Body text",
"default": "A short description of this section."
},
{
"type": "color",
"id": "background_color",
"label": "Background color",
"default": "#ffffff"
},
{
"type": "range",
"id": "column_count",
"label": "Columns",
"min": 1,
"max": 4,
"step": 1,
"default": 3
},
{
"type": "checkbox",
"id": "show_dividers",
"label": "Show dividers",
"default": true
}
],
"blocks": [
{
"type": "feature_item",
"name": "Feature",
"settings": [
{ "type": "text", "id": "title", "label": "Title", "default": "Feature" },
{ "type": "textarea", "id": "description", "label": "Description", "default": "" }
]
}
],
"presets": [
{
"name": "Feature Grid",
"blocks": [
{ "type": "feature_item", "settings": { "title": "Fast", "description": "Built for performance." } },
{ "type": "feature_item", "settings": { "title": "Flexible", "description": "Customize anything." } },
{ "type": "feature_item", "settings": { "title": "Reliable", "description": "99.9% uptime." } }
]
}
]
}
{%- endschema -%}Inline Editing
Add data-cartly-edit="<settingId>" to any HTML element to make it directly editable when the visual editor preview iframe is active. Clicking the element selects the corresponding setting in the sidebar and enables inline text editing.
<!-- Any element with data-cartly-edit="<settingId>" becomes
directly editable when the visual editor is open. -->
<h2 data-cartly-edit="heading">
{{ section.settings.heading }}
</h2>
<!-- Block-level fields require both attributes: -->
<p
data-cartly-edit="body_text"
data-block-id="{{ block.id }}"
>
{{ block.settings.body_text }}
</p>
<!-- Image pickers show a media-selector overlay on click: -->
<img
data-cartly-edit="hero_image"
src="{{ section.settings.hero_image | img_url: '1200x' }}"
alt="{{ section.settings.heading }}"
/>For block-level settings, add data-block-id="{{ block.id }}" alongsidedata-cartly-edit so the editor knows which block instance owns the setting.
Code Editor Workflow
Open the code editor at Admin → Online Store → Themes → Edit Code. The file tree on the left shows every file in the three-layer resolver with one of three badges:
| Badge | Meaning |
|---|---|
| Synced | Stock file from the platform embed. No DB row. Platform updates flow in automatically. |
| Custom | Merchant has forked this file. A DB row exists. Use "Compare with original" to diff against the embed version. Use "Revert to default" to delete the DB row and go back to Synced. |
| New | Merchant-created file with no embed counterpart. Deleting it removes it entirely. |
Filter the tree with the All / Modified / Synced chips and the live count badges to quickly locate customized files.
Forking a stock file
- Click a Synced file — it opens read-only with a blue banner.
- Click Edit file (or press ⌘E) to confirm the fork in the modal.
- After confirmation the file becomes editable. The first save creates the DB row and records the
upstream_hashsnapshot.
Upstream updated banner
If the platform ships a new embed version of a file you have forked, an amber banner appears: This file has been updated upstream. You can click View diff to open the Monaco diff editor (left = upstream, right = your fork), or Sync upstream to replace your fork with the new embed version (this deletes your DB row).
Use Sync All upstream in the toolbar to bulk-sync all forked files that have upstream changes.
Preview button
Click Preview in the toolbar to open your storefront in a new tab with the current (possibly unsaved) theme state. The button calls POST /admin/theme/library/:id/preview-token and appends the signed token to the storefront URL. Tokens expire in 15 minutes.
// Generate a signed preview URL for a theme install
const ADMIN_JWT = 'your_admin_jwt';
const THEME_ID = 'uuid-of-theme-install';
const { token } = await fetch(
`https://cartly.pro/admin/theme/library/${THEME_ID}/preview-token`,
{
method: 'POST',
headers: { 'Authorization': `Bearer ${ADMIN_JWT}` },
}
).then(r => r.json());
// Preview URL — open in a new tab; token expires in 15 minutes
const previewUrl = `https://your-shop.mycartly.pro/?preview_token=${token}`;Creating a New Section
- In the code editor file tree, click the + icon (New file).
- In the modal, choose Section as the file type and give it a name.
- Cartly generates a working scaffold with full HTML markup, five typed settings (text, color, range, checkbox, image_picker), and a preset with seeded defaults — ready to use immediately in the + Add panel.
The presets array in the schema is what makes the section visible in the + Add panel. Every preset entry provides a ready-to-use configuration so merchants can add the section with one click without configuring it from scratch. Without at least one preset, the section does not appear in the Add panel.
After saving, the new section is immediately available in the Visual Editor + Add panel. It starts as a New file (no embed counterpart).
Theme Editor DX (v1.16)
Wave 2 of v1.16 ships four developer-facing improvements to the theme editor: real-time SSE hot reload, stricter {%- schema -%} validation, alternate templates, an in-editor "+ Create custom section" flow, and an offline schema audit script you can wire into your pre-commit hook.
SSE Hot Reload
Every write to a theme install (file save, delete, rename, publish, or GitHub sync) is broadcast over a per-install Server-Sent Events stream. The visual editor preview iframe and the code editor both subscribe so edits in one tab appear instantly in another. Custom admin extensions (e.g. an embedded app that mirrors theme state) can subscribe the same way.
| Endpoint | Purpose |
|---|---|
POST /admin/theme/library/:id/events/token | Mint a 60-second single-use stream token. Browser EventSource can't set custom headers, so the JWT never goes in the URL. |
GET /admin/theme/library/:id/events?stream_token=<t> | Open the SSE stream. The token is bound to (shop_id, install_id) and DEL'd from Redis on first open — capture-replay safe. |
Event names emitted on the stream:
file_updated— a file was created or savedfile_deleted— a forked file was reverted or deletedfile_renamed— a file was renamed in the editorpublished— a draft template (*.draft.json) was promoted to its base pathgithub_synced— a GitHub push or sync overwrote files
Each event carries a JSON payload of shape { kind, install_id, file_path, version, at }. The frontend dedupes on version so reconnects (which do not replay history) are safe.
// Subscribe to theme file-save events from the admin session.
//
// Browsers can't set Authorization headers on EventSource, so the
// editor first POSTs to mint a 60-second single-use stream token,
// then opens the SSE stream with ?stream_token=<token>. The token
// is bound to (shop_id, install_id) and DEL'd from Redis on first
// open — capture-replay safe.
//
// See frontend/app/lib/theme-sse.ts for the production helper.
async function openThemeEvents(themeId) {
// Mint a stream token (uses the admin session cookie).
const tokenRes = await fetch(
`/_proxy/theme-event-token?themeId=${themeId}`,
{ method: 'POST', credentials: 'include' }
);
if (!tokenRes.ok) return null;
const { token } = await tokenRes.json();
const url = `/admin/theme/library/${themeId}/events?stream_token=${token}`;
const es = new EventSource(url, { withCredentials: true });
// Server emits one named event per write; payload is a JSON
// ThemeEvent { kind, install_id, file_path, version, at }.
es.addEventListener('file_updated', (e) => console.log('saved', JSON.parse(e.data)));
es.addEventListener('file_deleted', (e) => console.log('deleted', JSON.parse(e.data)));
es.addEventListener('file_renamed', (e) => console.log('renamed', JSON.parse(e.data)));
es.addEventListener('published', (e) => console.log('published',JSON.parse(e.data)));
es.addEventListener('github_synced', (e) => console.log('git sync', JSON.parse(e.data)));
return () => es.close();
}Schema Validation Rules
The Monaco editor lints {%- schema -%} blocks on every keystroke and refuses to save a section with errors. The same rules run offline via scripts/audit-section-schemas.mjs. Source of truth: frontend/app/components/code-editor/liquidLint.ts (thecheckSectionSchema, validateSchemaShape and validateFieldArray helpers).
| Rule | Severity | Message | How to fix |
|---|---|---|---|
| Missing schema block | warning | "Section file is missing {% schema %} block." | Append a {%- schema -%}…{%- endschema -%} block with at least name and one presets[] entry. |
| Invalid JSON | error | "JSON parse: …" | Watch for trailing commas and unquoted keys. |
settings not an array | error | '"settings" must be an array.' | Wrap settings in [ … ]. |
Field missing type | error | 'settings[i] is missing required "type" string.' | Add "type": "<known-type>". |
Field missing id (non-presentational) | error | 'settings[i] (type=text) is missing required "id" string.' | Add a unique id. Presentational fields (header, paragraph) are exempt. |
Duplicate id | error | 'Duplicate setting id "heading" (also at settings[2]).' | IDs must be unique within a settings array. |
Field missing label | error | 'settings[i] is missing required "label" string.' | Add a human-readable label. |
Unknown type | warning | 'has unknown field type "foo". Won't render in the visual editor.' | Use a known type (see frontend/app/lib/theme-schema-constants.ts FIELD_TYPE_MAP). |
range missing min/max/step | error | '(type=range) requires numeric "min", "max" and "step".' | Add all three as numbers. |
range min ≥ max | error | 'range min (5) must be < max (5).' | Fix the bounds. |
range step ≤ 0 | error | 'range step must be > 0.' | Use a positive step. |
range > 200 ticks | warning | 'range produces >200 ticks — slider will be unusable.' | Increase step or narrow the bounds. |
blocks not an array | error | '"blocks" must be an array.' | Wrap blocks in [ … ]. |
Block missing type / name | error | 'Block at index i is missing required "type" / "name" string.' | Add both fields to every block entry. |
presets not an array | error | '"presets" must be an array.' | Wrap presets in [ … ]. |
| No presets at all | warning | "no presets — won't appear in + Add panel" | Add at least one preset (system pages and entity-bound sections are exempt). |
Dynamic-source default on incompatible type | warning | "(type=checkbox) cannot bind to a metafield. Dynamic sources are only supported on text/number/color/image/url/richtext/select/ font_picker fields." | Drop the metafield binding or change the field type. |
| Malformed metafield path | warning | 'metafield path "foo.bar" is not in the form "owner.metafields.namespace.key".' | Use product.metafields.custom.lookbook etc. |
Alternate Templates
Alternate templates let merchants assign a non-default page layout to a single entity. The naming convention is templates/<base>.<suffix>.json where <base> is one of product, page, collection, article. Other base templates (cart, search, blog, 404, account, login, register) are singletons — they don't accept suffix variants.
// templates/product.lookbook.json — alternate product template
//
// Naming convention: <base>.<suffix>.json where <base> is one of
// product | page | collection | article. The suffix becomes
// selectable in the admin entity edit form's "Theme template" picker.
// Other base templates (cart, search, blog, 404, account, login,
// register) are singletons — no suffix variants.
{
"name": "Lookbook",
"sections": {
"hero": { "type": "image-banner", "settings": { "heading": "Lookbook" } },
"main": { "type": "main-product" },
"story": { "type": "rich-text", "settings": { "body": "<p>Editorial copy…</p>" } }
},
"order": ["hero", "main", "story"]
}Publishing: create the file in the code editor (or commit it via GitHub sync). It's discovered automatically by the resolver — no extra registration step.
Per-entity assignment: on the admin product / collection / page / article edit page, a Theme template dropdown lists every variant the active theme exposes. Picking Lookbook writes template_suffix = "lookbook" on the entity, which the storefront router reads to pick templates/product.lookbook.json instead of the default. The dropdown auto-hides when only the default exists, so themes without alternates never show a useless one-option select.
Backend reference: variants are listed by GET /admin/theme/library/:id/page-templates?type=<base> (see backend/internal/theme/handler_page_templates.go ListPageTemplates); the frontend picker lives at frontend/app/components/admin/ThemeTemplatePicker.tsx.
+ Create custom section (visual editor)
In the visual editor's left sidebar, scroll to the bottom of the + Add panel and click + Create custom section. A dialog opens that lets you:
- Pick a scaffold variant — minimal, hero, grid, carousel, FAQ, etc. Each variant ships a working Liquid template with markup, typed settings, and a preset.
- Give the section a name. The slug becomes its file path:
sections/<slug>.liquid. - Confirm. The file is written to the install (creating a DB row), the editor opens it in Monaco for further customisation, and it appears in the + Add panel immediately for one-click insertion onto any template.
The same scaffolds are available from the code editor's + New file → Section flow. Both paths route through frontend/app/lib/theme-scaffolds.ts, so a section created either way validates against the same schema rules.
Pre-commit gate: scripts/audit-section-schemas.mjs
Theme developers shipping their own boilerplate can run the same validators offline. The script walks backend/internal/theme/templates/boilerplate/sections/, parses each {%- schema -%} block, and reports errors / warnings. Exit code is 1 on any error, 0 otherwise.
# Run on demand
node scripts/audit-section-schemas.mjs
# Sample output
=== hero.liquid ===
ERR settings[2] (type=text) is missing required "id"
WARN settings[5] range produces > 200 ticks — slider unusable
--- Audit: 42 sections, 1 error(s), 1 warning(s) ---Wire it into Husky so broken schemas can't land on main:
# .husky/pre-commit
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
# Block commits that introduce broken section schemas.
# Mirrors the Monaco lint rules (frontend/app/components/code-editor/liquidLint.ts)
# so what fails locally also fails in the visual editor's + Add panel.
node scripts/audit-section-schemas.mjsThe audit script imports its known field-type set directly from frontend/app/lib/theme-schema-constants.ts (FIELD_TYPE_MAP) — when a new field type lands in the shared constants, the audit picks it up automatically with no manual sync step.
API Reference
// List files in a theme install (includes embed_content + upstream_changed flags)
const { files } = await fetch(
`https://cartly.pro/admin/theme/library/${THEME_ID}/files`,
{ headers: { 'Authorization': `Bearer ${ADMIN_JWT}` } }
).then(r => r.json());
// files[0] = {
// key: "sections/hero.liquid",
// source: "embed", // "db" | "embed" | "boilerplate"
// upstream_changed: false, // true when embed shipped a newer version after merchant forked
// embed_content: "…", // present only when source === "embed"
// }
// Get a single file — with embed_content for diff comparison
const file = await fetch(
`https://cartly.pro/admin/theme/library/${THEME_ID}/files/sections%2Fhero.liquid`,
{ headers: { 'Authorization': `Bearer ${ADMIN_JWT}` } }
).then(r => r.json());
// Update (fork) a file — optimistic CAS via version field
await fetch(
`https://cartly.pro/admin/theme/library/${THEME_ID}/files/sections%2Fhero.liquid`,
{
method: 'PUT',
headers: {
'Authorization': `Bearer ${ADMIN_JWT}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
content: '<section>…</section>\n{%- schema -%}…{%- endschema -%}',
version: file.version, // CAS guard — prevents overwriting concurrent saves
}),
}
);
// Delete a forked file (action: "reverted" | "deleted")
await fetch(
`https://cartly.pro/admin/theme/library/${THEME_ID}/files/sections%2Fhero.liquid`,
{
method: 'DELETE',
headers: { 'Authorization': `Bearer ${ADMIN_JWT}` },
body: JSON.stringify({ action: 'reverted' }),
}
);
// Bulk sections-source (aggregates DB ∪ embed — used by + Add panel)
const { sections } = await fetch(
`https://cartly.pro/admin/theme/library/${THEME_ID}/sections-source`,
{ headers: { 'Authorization': `Bearer ${ADMIN_JWT}` } }
).then(r => r.json());| Method | Path | Description |
|---|---|---|
| GET | /admin/theme/library/:id/files | List all files with source, badges, and upstream_changed flag |
| GET | /admin/theme/library/:id/files/:key | Get a single file — includes embed_content for diff and upstream_changed |
| PUT | /admin/theme/library/:id/files/:key | Create or update a file (fork). CAS via version field. |
| DELETE | /admin/theme/library/:id/files/:key | Delete or revert a file. Body: action: "reverted" | "deleted" |
| GET | /admin/theme/library/:id/sections-source | Bulk section metadata (DB ∪ embed) — used by the + Add panel |
| GET | /admin/theme/library/:id/events | SSE stream of file-save events for real-time editor sync |
| POST | /admin/theme/library/:id/preview-token | Generate a signed 15-minute storefront preview token |
All /admin/* endpoints require a valid admin JWT in the Authorization: Bearer <token> header. The :key path parameter must be URL-encoded (e.g. sections%2Fhero.liquid).