Build a Shopify theme from scratch, with Liquid · Part 2 of 6
Liquid on the product and collection pages
Objects, tags and filters learned where they matter: a gallery from product.media, a price snippet, a variant picker from options_with_values with availability per value, sorting through sort_by, and cards with badges and hover images.
By Abhishek Fouzdar
This part is Liquid itself, learned on the two pages that use most of it. The product page gets a gallery built from product.media, a price snippet that knows about sale prices, a variant picker rendered from product.options_with_values with availability per value, a quantity field and accordions. The collection page gets sorting the way Shopify expects it, badges, a hover image on every card and eager loading for the first row. Everything is Liquid; the three lines of JavaScript at the end could be deleted and the pages would still work. Part 1 built the theme that renders.

Objects, tags, filters
Liquid has three kinds of thing, and every file in the theme is made of them.
Objects are the data Shopify hands the template: product, collection, cart, shop, settings, section, request. They have properties (product.title), some of which are objects or arrays themselves (product.variants, product.media). Which objects exist depends on the page: product exists on a product page and nowhere else, collection on a collection page and, usefully, on a product page reached from a collection.
Tags are logic: {% if %}, {% unless %}, {% for %}, {% assign %}, {% render %}, {% paginate %}, {% form %}, {% schema %}. A tag does not output anything by itself.
Filters transform a value on its way out: {{ product.price | money }}, {{ title | escape }}, {{ 'cart.title' | t }}. They chain left to right, and the image filters are the longest chains you will write.
Two habits that make Liquid readable. {%- and -%} strip the whitespace around a tag, so a page full of logic does not render as a page full of blank lines; the theme uses them everywhere a tag is on its own line. And {% liquid %} opens a block where every line is a tag without its own delimiters:
{%- liquid
assign current = product.selected_or_first_available_variant
assign images = product.media | where: 'media_type', 'image'
assign featured = current.featured_media | default: product.featured_media
-%}
Three assignments, three Liquid ideas. selected_or_first_available_variant is the variant the page is about: the one in the URL's ?variant= parameter, else the first one that can be bought. where filters an array by a property, here keeping only images out of a media list that could hold video and 3D models. default supplies a fallback when the left side is empty.
The price snippet
Prices appear on cards, on the product page and later in the cart, and they have three states: a plain price, a sale price with the old one struck through, and a range when variants differ. One snippet handles all of it, and the rest of the theme never writes | money for a product again.
{%- liquid
assign size = size | default: 'sm'
if variant
assign price = variant.price
assign compare = variant.compare_at_price
assign varies = false
else
assign price = product.selected_or_first_available_variant.price
assign compare = product.selected_or_first_available_variant.compare_at_price
assign varies = product.price_varies
endif
assign on_sale = false
if compare > price
assign on_sale = true
endif
-%}
<span class="{% if size == 'lg' %}text-2xl{% else %}text-sm{% endif %} font-semibold {% if size == 'sm' %}font-normal text-ink-2{% endif %}">
{%- if on_sale -%}
<span class="text-[#B42318]">{{ price | money }}</span>
<s class="text-ink-2/70 font-normal">{{ compare | money }}</s>
{%- elsif varies and variant == nil -%}
{{ product.price_min | money }} – {{ product.price_max | money }}
{%- else -%}
{{ price | money }}
{%- endif -%}
</span>
{% render 'price', product: product %} on a card, {% render 'price', variant: current, size: 'lg' %} on the product page. A snippet sees only what it is given, so the first line's size | default: 'sm' is how optional arguments work. Prices are integers in the smallest unit, 120000 for ₹1,200.00, and money formats them in the store's own format, which is why they read "Rs. 1,200.00" on this store and would read "€1.200,00" on another, with no change to the theme.
The gallery
product.media is every image, video and model on the product, in the order the merchant set. The gallery renders the images twice, as thumbnails and as the main column:
<div class="grid gap-4 md:grid-cols-[88px_minmax(0,1fr)]">
<div class="order-2 md:order-1 flex md:flex-col gap-2.5 overflow-x-auto">
{%- for media in images -%}
<a href="#media-{{ media.id }}" class="block shrink-0 w-[72px] md:w-full aspect-square rounded-[10px] overflow-hidden bg-ground-2 border-2 {% if media.id == featured.id %}border-ink{% else %}border-transparent{% endif %}" aria-label="Image {{ forloop.index }} of {{ images.size }}">
{{ media | image_url: width: 180 | image_tag: class: 'w-full h-full object-cover', widths: '90, 180', sizes: '88px', loading: 'lazy' }}
</a>
{%- endfor -%}
</div>
<div class="order-1 md:order-2 flex flex-col gap-4">
{%- for media in images -%}
{%- liquid
# The first image is what the page is for: load it eagerly, the rest lazily.
if forloop.first
assign loading = 'eager'
else
assign loading = 'lazy'
endif
-%}
<div id="media-{{ media.id }}" class="rounded-tile overflow-hidden bg-ground-2 aspect-[4/5] {% unless forloop.first %}scroll-mt-24{% endunless %}">
{{ media | image_url: width: 1400 | image_tag: class: 'w-full h-full object-cover', widths: '600, 900, 1200, 1400', sizes: '(min-width: 768px) 50vw, 100vw', loading: loading }}
</div>
{%- endfor -%}
</div>
</div>
image_url: width: 1400 asks the CDN for the image at that width and image_tag turns it into an <img> with srcset at the widths given, a sizes attribute, and the width and height the browser needs to reserve space before the image arrives. That chain is the whole of responsive images in a theme; Shopify's docs call it the recommended implementation, and the alternative is twenty lines of hand-built URLs that miss the format conversion the CDN does for free. Four to six widths is enough; more hurts caching.
forloop is the object every for gives you: first, last, index, index0, length. The first image loads eagerly because it is the page's largest content; the others wait. The thumbnails are anchor links to the images below them, which works with no script and on any device; part 4 makes the gallery follow the variant picker.
The variant picker
This is the part of a product page that themes get wrong, because the data model is subtler than it looks. A product has options (Colour, Size), each option has values (Indigo, Rust, Charcoal), and a variant is one combination of values with its own price, stock and image. Not every combination exists, and not every one that exists is in stock.
product.options_with_values gives the options with their values as product_option_value objects, and each value knows four things in the context of what is currently selected: selected, available (whether any purchasable variant has it, given the other selections), variant (the variant you would land on by choosing it), and swatch (a colour or image, when the merchant has set one on the option).
{%- for option in product.options_with_values -%}
<fieldset class="flex flex-col gap-2.5 border-0 p-0 m-0">
<legend class="text-sm font-semibold mb-2.5">{{ option.name }}: <span class="font-normal text-ink-2">{{ option.selected_value }}</span></legend>
<div class="flex flex-wrap gap-2.5">
{%- for value in option.values -%}
{%- liquid
assign swatch = value.swatch
if value.variant
assign href = value.variant.url
else
assign href = product.url
endif
-%}
{%- if swatch -%}
<a href="{{ href }}" class="block w-9 h-9 rounded-full border-2 {% if value.selected %}border-ground shadow-[0_0_0_2px_var(--lantern-ink)]{% else %}border-transparent shadow-[0_0_0_1px_var(--lantern-line)]{% endif %} {% unless value.available %}opacity-40{% endunless %}" style="background: {{ swatch.color | default: '#ddd' }}" aria-label="{{ value }}{% unless value.available %}, {{ 'products.product.sold_out' | t }}{% endunless %}" {% if value.selected %}aria-current="true"{% endif %}></a>
{%- else -%}
<a href="{{ href }}" class="min-h-11 px-4 inline-flex items-center rounded-full border text-sm font-medium {% if value.selected %}bg-ink text-ground border-ink{% else %}bg-white border-line hover:border-ink{% endif %} {% unless value.available %}line-through text-ink-2{% endunless %}" {% if value.selected %}aria-current="true"{% endif %}>{{ value }}</a>
{%- endif -%}
{%- endfor -%}
</div>
</fieldset>
{%- endfor -%}
<input type="hidden" name="id" value="{{ current.id }}">
Each value is a link to value.variant.url, which is the product URL with ?variant= set, so choosing a colour loads the page with that variant selected, its price shown, its image marked in the thumbnails, and the other option's values re-evaluated for availability. No JavaScript, correct for every combination, and shareable: the URL is the selection. The hidden id input is what the {% form 'product' %} posts to the cart; it is the selected variant's id, which is all the cart needs.
The store's cushion cover makes a good test. Indigo in 16" is in stock. Click Rust:

Rust in 16" is sold out, so the 16" value is struck through and the button says so, while 20" stays available because Rust in 20" exists and has stock. That is value.available doing the work, "top-down" as the docs put it: a value is available if any purchasable variant under the current selection has it. The legend reads "Colour: Rust" from option.selected_value.
The swatch branch renders when the merchant has given an option value a colour in the admin; this store has not, so every value renders as a pill. The code is there because the design has swatches, and the day the merchant adds colours they appear.
The form itself:
{%- form 'product', product, class: 'flex flex-col gap-5', id: 'ProductForm' -%}
...the picker...
<div class="flex flex-wrap gap-3 items-stretch">
<div class="inline-flex items-center rounded-full border border-line bg-white">
<label for="Quantity" class="sr-only">{{ 'products.product.quantity' | t }}</label>
<input id="Quantity" type="number" name="quantity" value="1" min="1" class="w-16 min-h-11 text-center bg-transparent font-semibold">
</div>
<button type="submit" class="btn flex-1 min-w-[220px]" {% unless current.available %}disabled{% endunless %}>
{%- if current.available -%}{{ 'products.product.add_to_cart' | t }} · {{ current.price | money }}{%- else -%}{{ 'products.product.sold_out' | t }}{%- endif -%}
</button>
</div>
{%- endform -%}
{% form 'product', product %} writes the <form> with the right action, method and the hidden fields Shopify needs. Submitting it adds the variant to the cart and sends the buyer to the cart page; part 4 intercepts that to open a drawer instead, and this form is what it falls back to.
Cards and the collection
The card from part 1 learns three things: the second image shows on hover, a Sale or Sold out badge sits in the corner, and the first row of a collection loads eagerly:
{%- liquid
assign loading = loading | default: 'lazy'
assign second = product.media[1]
assign on_sale = false
if product.compare_at_price > product.price
assign on_sale = true
endif
-%}
<a href="{{ product.url }}" class="block group">
<div class="relative aspect-[4/5] rounded-[14px] overflow-hidden bg-ground-2">
{%- if product.featured_image -%}
{{ product.featured_image | image_url: width: 800 | image_tag: class: 'w-full h-full object-cover transition-opacity duration-300', widths: '400, 600, 800', sizes: '(min-width: 1024px) 25vw, (min-width: 768px) 33vw, 50vw', loading: loading }}
{%- if second and second.media_type == 'image' -%}
{{ second | image_url: width: 800 | image_tag: class: 'absolute inset-0 w-full h-full object-cover opacity-0 group-hover:opacity-100 transition-opacity duration-300', widths: '400, 600, 800', sizes: '(min-width: 1024px) 25vw, (min-width: 768px) 33vw, 50vw', loading: 'lazy', alt: '' }}
{%- endif -%}
{%- endif -%}
{%- unless product.available -%}
<span class="absolute top-3 left-3 rounded-full bg-ground px-2.5 py-1 text-[11px] font-semibold tracking-[0.06em] uppercase">{{ 'products.product.sold_out' | t }}</span>
{%- elsif on_sale -%}
<span class="absolute top-3 left-3 rounded-full bg-ground px-2.5 py-1 text-[11px] font-semibold tracking-[0.06em] uppercase">{{ 'products.product.on_sale' | t }}</span>
{%- endunless -%}
</div>
<h3 class="mt-3 text-base font-semibold leading-snug group-hover:text-accent">{{ product.title }}</h3>
<p class="mt-1">{% render 'price', product: product %}</p>
</a>
product.media[1] is array indexing; unless ... elsif is Liquid's slightly odd way of saying "if not available, else if on sale". The collection page passes loading: 'eager' for the first four cards and 'lazy' for the rest, by checking forloop.index <= 4 before each render.
Sorting is a form:
{%- liquid
assign sort_by = collection.sort_by | default: collection.default_sort_by
-%}
<form method="get" action="{{ collection.url }}" class="flex items-center gap-3 text-sm self-end">
<label for="SortBy">{{ 'collections.sorting.title' | t }}</label>
<select id="SortBy" name="sort_by" class="min-h-11 rounded-full border border-line bg-white px-4">
{%- for option in collection.sort_options -%}
<option value="{{ option.value }}" {% if option.value == sort_by %}selected{% endif %}>{{ option.name }}</option>
{%- endfor -%}
</select>
<noscript><button type="submit" class="btn btn-ghost min-h-11">{{ 'collections.sorting.apply' | t }}</button></noscript>
</form>
Shopify sorts collections server-side from a sort_by query parameter, and collection.sort_options lists the values it accepts with their labels, in the store's language. The theme's only job is to send the parameter. A GET form does that, noscript shows an Apply button when there is no JavaScript, and with JavaScript the select submits itself on change:
document.querySelectorAll('#SortBy').forEach((select) => {
select.addEventListener('change', () => select.form.requestSubmit());
});

{% paginate collection.products by section.settings.per_page %} is unchanged from part 1 and worth one more sentence: a collection's products are limited to 50 per request, so pagination is not optional, and inside the block paginate.parts gives the page links already computed.
shopify theme check
40 files inspected with no offenses found.
What went wrong
Unknown filter 'ternary' from Theme Check. I wrote loading: forloop.first | ternary: 'eager', 'lazy' out of habit from another template language. Liquid has no ternary; the condition became a four-line if in a {% liquid %} block. Theme Check caught it before the push did, which is what it is for.
Choosing a variant marked the right thumbnail but did not scroll to it. Expected, since the thumbnails are plain anchors and the page loads at the top; it is still slightly surprising on first use. Part 4 switches the gallery when the variant changes.
The store has one collection, the automatic "frontpage" with a single product, so "Shop by collection" on the home page has nothing to show yet. Part 3 needs real collections; they are a few minutes in the admin with automated conditions on the product tags the store already has.
Part 3 is the theme editor's side of things: sections with blocks, settings of every type, the blocks/ directory for theme blocks, the font picker that finally gives the theme its typefaces, and the home page built from sections a merchant can rearrange.
New posts by email
Get new posts by email. Nothing else, no digests, unsubscribe in one click.
Comments
Comments are GitHub Discussions in shipbytes/discussions. Sign in with GitHub to post.
In this series
2 / 6- OverviewBuild a Shopify theme from scratch, with Liquid
- Part 1The anatomy of a theme, and one that renders
- Part 2Liquid on the product and collection pages
- Part 3Sections, blocks and the theme editor
- Part 4Variants without reloads, the Cart API and a cart drawer
- Part 5Search, pagination, metafields, translations and customers
- Part 6Performance, accessibility, Theme Check and publishing