A grocery product card has two jobs: display comparable prices and send the correct variant and quantity to the cart. Freshmart provides a visual reference for the card and the shopping aisle.
Render the unit price for the selected variant
{%- assign variant = product.selected_or_first_available_variant -%}
{%- if variant.unit_price_measurement -%}
<span class="fm-unit-price">
{{ variant.unit_price | unit_price_with_measurement: variant.unit_price_measurement }}
</span>
{%- endif -%}
Configure total measurement and base measurement on the product or variant. Use the same comparison unit within a category. On a pack-size change, update both the label and the selected variant ID.
Handle the cart response before continuing
async function addSelection(items) {
const root = window.Shopify.routes.root;
let message = '';
try {
const response = await fetch(root + 'cart/add.js', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ items })
});
if (!response.ok) {
const error = await response.json().catch(() => null);
message = error?.description || '有商品未按所选数量加入。';
}
} catch {
message = '未收到加购确认,请查看当前购物车。';
}
const currentCart = await fetch(root + 'cart.js');
if (!currentCart.ok) throw new Error('暂时无法读取购物车');
return { cart: await currentCart.json(), message };
}
Disable the submit button while adding the selection. The Cart API can add the available quantity when the requested quantity exceeds stock. Reconcile the result against the latest cart and show it to the shopper before another attempt.
Test the cases that change the outcome
- Add across two categories and switch pack sizes.
- Test a variant already in the cart, a partial-stock response and a network interruption.
- Confirm the actual discounts, currency and shipping conditions at checkout.
References: Shopify unit price filter, Ajax Cart API and Orbix Studio's Freshmart project.
Top comments (0)