Skip to content
Tutorials Center
My learning

Topics

Lesson 57 of 61 ยท Projects

Project: A Size Guide with Metaobjects

Build a size guide on a Shopify product page: define a metaobject, link it with a product metafield, render an accessible table in a modal and add safe fallbacks.

Clothing, shoes and furniture share a problem: the standard product fields cannot hold a size chart. A chart is structured data with a title, column headings and many rows, and the same chart usually applies to dozens of products ("all our women's tops"). Pasting an HTML table into every product description works for about a week and then falls apart when one number needs fixing.

Metaobjects solve this. You define a custom content type once ("Size guide"), merchants create entries (one chart per entry), and each product points at the entry it should use through a metafield. The theme reads the entry, renders the table in a modal, and falls back gracefully when a product has no chart. This project walks through the whole path: the data model, the Liquid, the modal, the fallback chain and some data hygiene checks. If you have not met these tools yet, read Metafields in Themes and Metaobjects in Themes first.

The Liquid and admin steps target current Online Store 2.0 themes. Real metaobject and metafield data exists only in a Shopify store, so the code is shown read-only and the runnable stand-ins use plain JavaScript objects with the same shape. Field names and the exact admin labels may change, so check the current admin when you set it up.

Step 1: model the data

Start in the admin under Content, then Metaobjects, and create a definition. Give it the name Size guide and the type handle size_guide. The fields below are a good starting point:

Field Type Purpose
title Single line text Shown as the modal heading, for example "Women's tops"
intro Multi-line text A sentence on how to measure
unit_note Single line text For example "Measurements are body sizes in centimeters"
table JSON The chart: headings and rows

The JSON field keeps the chart in one place and lets you validate its shape in code. A chart looks like this:

JSON
{
  "headers": ["Size", "Chest (cm)", "Waist (cm)", "Hips (cm)"],
  "rows": [
    ["S", "86", "71", "92"],
    ["M", "94", "79", "100"],
    ["L", "102", "87", "108"]
  ]
}

There are other ways to model rows. A list of metaobject references (each row is its own entry with fields) is friendlier for merchants who do not want to write JSON, and a list of single-line text values ("S|86|71|92") is simple but fragile. Choose JSON when a developer or an import tool maintains the charts, and row entries when non-technical editors do. The Liquid below shows JSON because it keeps the example short.

Two settings matter for the theme. The definition (and its entries) must be available to the storefront, and entries should be active if the definition uses publishing statuses, otherwise Liquid sees nothing. When a chart does not show up, check these first.

Then link products to charts. Create a product metafield definition in Settings, then Custom data, with the namespace and key custom.size_guide, the type Metaobject reference, and the allowed definition set to Size guide. Merchants now see a "Size guide" picker on each product and choose an entry.

flowchart LR
  P["Product<br/>metafield custom.size_guide"] -->|"references"| E["Metaobject entry<br/>Women's tops"]
  E --> T["table (JSON)<br/>headers + rows"]
  S["Shop metafield<br/>custom.default_size_guide"] -.->|"fallback"| E2["Default entry"]

Each product points to one entry; a shop-level default can cover products that have none.

Step 2: read the entry in Liquid

A metaobject reference metafield returns the entry object through .value. Its fields are read with dot notation, and each field also has .value:

LIQUID
{%- assign guide = product.metafields.custom.size_guide.value -%}

{%- if guide != blank -%}
  <h2>{{ guide.title.value | escape }}</h2>
  <p>{{ guide.intro.value | escape }}</p>
{%- endif -%}

For single-line and multi-line text, guide.title also prints directly, but .value is the explicit form and works the same for every field type. The JSON field is parsed for you, so guide.table.value.headers is an array and guide.table.value.rows is an array of arrays.

The fallback chain

A product may not have a chart, and a store with hundreds of products will always have a few that were missed. Decide the order of precedence once, in the snippet:

  1. the product's own custom.size_guide;
  2. otherwise a shop-wide default stored in a shop metafield, custom.default_size_guide;
  3. otherwise show nothing: no button, no empty modal.
LIQUID
{%- liquid
  assign guide = product.metafields.custom.size_guide.value
  if guide == blank
    assign guide = shop.metafields.custom.default_size_guide.value
  endif
-%}

Hiding the trigger entirely when there is no data matters. A "Size guide" button that opens an empty box is worse than no button.

Step 3: render the table

A size chart is tabular data, so use a real <table> with a caption and header cells. That gives screen reader users row and column navigation for free:

LIQUID
{%- liquid
  assign headers = guide.table.value.headers
  assign rows = guide.table.value.rows
-%}

{%- if headers != blank and rows != blank -%}
  <table class="size-table">
    <caption>{{ guide.title.value | escape }}</caption>
    <thead>
      <tr>
        {%- for heading in headers -%}
          <th scope="col">{{ heading | escape }}</th>
        {%- endfor -%}
      </tr>
    </thead>
    <tbody>
      {%- for row in rows -%}
        <tr>
          {%- for cell in row -%}
            {%- if forloop.first -%}
              <th scope="row">{{ cell | escape }}</th>
            {%- else -%}
              <td>{{ cell | escape }}</td>
            {%- endif -%}
          {%- endfor -%}
        </tr>
      {%- endfor -%}
    </tbody>
  </table>
{%- else -%}
  <p>This size guide is not available yet.</p>
{%- endif -%}

The first cell of each row is a row header (th scope="row"), so a screen reader reading the cell "94" under "Chest" also announces "M". Everything is passed through escape, because merchants and imports can put anything in a JSON cell.

On narrow screens, wide tables overflow. Wrap the table in a container with overflow-x: auto and make that container focusable (tabindex="0", with a label) so keyboard users can scroll it:

CSS
.size-table-wrap { overflow-x: auto; }
.size-table { border-collapse: collapse; width: 100%; }
.size-table th, .size-table td { padding: 0.5rem 0.75rem; border: 1px solid var(--color-border); text-align: left; }
.size-table tbody tr:nth-child(even) { background: var(--color-surface-alt); }

Check the data before you trust it

JSON is flexible, which means it can be wrong: a row with one cell missing shifts every value under the wrong heading. A defensive snippet checks the shape and refuses to draw a broken chart. In Liquid you can compare row.size with headers.size in the loop and skip bad rows. The stand-in below does the same validation in JavaScript, where it is easier to see, and also shows the fallback chain.

JS Stand-in: resolve a guide, validate it and print the table

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The scarf has no chart of its own, so it uses the shop default. The broken entry is rejected with specific messages instead of showing a misleading table, and the merchant (or you) can fix the row.

Step 4: the modal

A size guide opens in a modal so the shopper does not lose the product page. The platform gives you an excellent building block, the native <dialog> element. Opened with showModal(), it traps focus, makes the rest of the page inert, closes on Escape and restores focus to the opener. That removes most of the work you would otherwise do by hand (compare the manual focus handling in Building a Cart Drawer).

LIQUID
{%- if guide != blank -%}
  <size-guide>
    <button type="button" class="link" data-open aria-haspopup="dialog">
      {{ 'products.product.size_guide' | t }}
    </button>

    <dialog class="size-dialog" aria-labelledby="SizeGuideTitle-{{ section.id }}">
      <div class="size-dialog__head">
        <h2 id="SizeGuideTitle-{{ section.id }}">{{ guide.title.value | escape }}</h2>
        <button type="button" data-close aria-label="{{ 'accessibility.close' | t }}">&times;</button>
      </div>
      <p>{{ guide.intro.value | escape }}</p>
      <div class="size-table-wrap" tabindex="0" role="region"
           aria-label="{{ guide.title.value | escape }}">
        {% render 'size-table', guide: guide %}
      </div>
      <p class="size-note">{{ guide.unit_note.value | escape }}</p>
    </dialog>
  </size-guide>
{%- endif -%}

The trigger text comes from a locale key through the t filter (see Translations, Markets and Localization) so it can be translated. The behavior is a tiny custom element:

JavaScript
class SizeGuide extends HTMLElement {
  connectedCallback() {
    const dialog = this.querySelector('dialog');
    this.querySelector('[data-open]').addEventListener('click', () => dialog.showModal());
    this.querySelector('[data-close]').addEventListener('click', () => dialog.close());
    dialog.addEventListener('click', (event) => {
      if (event.target === dialog) dialog.close(); // click on the backdrop
    });
  }
}
customElements.define('size-guide', SizeGuide);

A click on the backdrop reports the dialog itself as the target, which is how the script tells it apart from a click inside the content. For this to work, give the dialog itself no padding and put the padding on an inner wrapper, otherwise a click on the padding also counts as a backdrop click. Because the <dialog> is in the HTML from the start, the table is available to search engines and works with the theme editor's section re-rendering; the JavaScript only opens it.

Step 5: the working stand-in

This stand-in is the whole feature in one frame: the product picks a guide (or falls back), the button appears only when there is data, the table is rendered with real header cells, and a cm / in switch converts the numbers. The conversion is a presentation feature: the stored data stays in centimeters, which keeps one source of truth.

Stand-in: size guide modal with unit toggle

Choose "Wool Scarf" to see the fallback and "Gift Card" to see the button disappear. Open the guide and press Escape: the dialog closes and focus returns to the button, because that is how native modal dialogs behave.

Maintenance and edge cases

  • Translations. Metaobject fields are the same for every language unless you translate them (the admin supports translating metaobject content). Keep chart headings short and consider moving the words into locale files if your headings are generic.
  • Variants. The chart describes body sizes, while the variant option says "M". If your option values are "Small", "Medium" and "Large", make the chart's first column use the same words, so shoppers can match them.
  • Performance. The chart is rendered inside the page for every product view. For very large charts, or many guides per page, render the dialog contents on demand with the Section Rendering API instead (The Section Rendering API).
  • Theme editor. Put the size guide button in a block of the main product section (see Blocks and Theme Blocks) so merchants can place it above or below the option pickers or remove it.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why use a metaobject for a size chart instead of pasting a table into the product description?

    A metaobject entry is shared structured data. Products point to it through a metafield, so correcting a number updates every product using the chart.
  2. 2. How does a product connect to its size guide entry?

    A metaobject reference metafield stores the link, and Liquid reads the entry from product.metafields.custom.size_guide.value.
  3. 3. A product has no size guide and no shop default exists. What should the theme do?

    A button that opens nothing frustrates shoppers. When there is no data, render nothing.
  4. 4. Why does the first cell of every body row use th scope="row"?

    Header cells let assistive technology tie each value to its row and column labels.
  5. 5. What does showModal() on a native dialog do for you?

    Native modal dialogs provide focus handling, inertness of the background and Escape-to-close, so you write much less code.

Summary

  • Model the chart once as a Size guide metaobject definition, with a JSON table field (or row entries for non-technical editors).
  • Link products with a custom.size_guide metafield of type metaobject reference; read it in Liquid with .value.
  • Use a precedence chain (product, then shop default, then nothing) and hide the button when there is no data.
  • Render a real table with caption, column headers and row headers; escape every cell and validate row lengths.
  • Open the chart in a native <dialog> with showModal(), and keep the stored data in one unit while the view converts it.

Next, build a feature that adds several products to the cart at once in Project: A Product Bundle Builder.