Skip to content

Blocks and fields ​

A block is one section of a page: a banner, a product grid, a FAQ. You write it once, in code. The merchant adds it to pages in Studio and fills in its fields.

A block has two halves. block.json lists the fields the merchant fills in. Block.vue renders them.

The block folder ​

Every block lives in its own folder under blocks/. The folder name is the block's apiId.

blocks/feature-banner/
  block.json      the fields Studio shows the merchant
  Block.vue       the Vue component that renders the block
  mock.json       the content a new block starts with when the merchant inserts it
  preview.json    optional: demo images for Storybook and the preview tile
  preview.png     generated by `pnpm previews`, never edited by hand

mock.json is real content, not filler. Write it the way a real shop would.

More: The block contract.

Build a block step by step ​

You will build a "Feature banner": a heading, a short text, an image and a button.

1. Create the folder ​

sh
pnpm exec eldra-theme scaffold block feature-banner

This writes block.json, Block.vue and mock.json with one placeholder field. You replace all three below.

2. Declare the fields ​

json
{
  "apiId": "feature-banner",
  "name": "Feature banner",
  "description": "A heading, a short text, one image and a button.",
  "icon": "photo",
  "category": "marketing",
  "version": 1,
  "fields": [
    {
      "fieldId": "heading",
      "name": "Heading",
      "type": "string",
      "isTitle": true,
      "localized": true,
      "validators": { "required": true, "maxLength": 120 }
    },
    {
      "fieldId": "text",
      "name": "Text",
      "type": "text",
      "localized": true,
      "helpText": "One or two sentences."
    },
    {
      "fieldId": "image",
      "name": "Image",
      "type": "media",
      "metadata": { "multiple": false, "framing": true }
    },
    {
      "fieldId": "button",
      "name": "Button",
      "type": "link",
      "localized": true,
      "metadata": { "kinds": ["product", "collection", "category", "page", "url"] }
    }
  ]
}

What the keys do:

  • fieldId is the key your component reads. Use camelCase.
  • name and helpText are what the merchant sees in Studio.
  • localized: true lets the merchant write the field once per language.
  • isTitle: true marks the field whose value names this block's content in Studio.
  • validators.required makes the field mandatory. It also makes the TypeScript property non-optional.
  • category and icon place the block in Studio's insert menu.

Set multiple on media fields

A media field holds several images unless you say otherwise. Add "multiple": false for a single image.

3. Write the starting content ​

mock.json is what Studio writes into the block when the merchant inserts it:

json
{
  "heading": "The winter edit is here",
  "text": "Wool throws, stoneware and candles for the darker months, made in small batches.",
  "button": { "kind": "url", "url": "/", "label": "Shop the edit" }
}

The image is missing on purpose. A media field is never in mock.json. Put a demo image in preview.json instead, so Storybook and the preview tile have something to show:

json
{
  "image": {
    "assetId": "demo-cta-split",
    "url": "/images/planters.webp",
    "altText": "Ceramic planters with green plants"
  }
}

4. Generate the types ​

sh
pnpm validate
pnpm exec eldra-theme types --blocks

validate checks your block.json. types writes .eldra/block-types.d.ts, which gives every block a typed EldraBlockEntry<'feature-banner'>. The dev server and the build refresh it too.

5. Render it ​

vue
<script setup lang="ts">
import { computed } from 'vue';
import { Button, Container, Section } from '@eldrajs/ui';
import { useEldraLink } from '@eldrajs/theme-vue';
import { stripStega } from '@eldrajs/theme-core/stega';
import { useBlockData } from '../../app/composables/useBlockData';
import EldraRouterLink from '../../app/components/EldraRouterLink.vue';
import UiImage from '../../app/components/ui/UiImage.vue';
import { isInternalHref, safeHref } from '../../app/utils/links';

const props = defineProps<{ entry: EldraBlockEntry<'feature-banner'> }>();
const { data, entryId } = useBlockData(props, 'feature-banner');
const resolveLink = useEldraLink();

const hasText = computed(() => stripStega(data.value.text ?? '').trim() !== '');

const button = computed(() => resolveLink(data.value.button));
const buttonHref = computed(() => safeHref(button.value?.href));
const buttonAs = computed(() =>
  buttonHref.value !== null && isInternalHref(buttonHref.value) ? EldraRouterLink : undefined
);
</script>

<template>
  <Section spacing="md">
    <Container width="wide">
      <div class="@tablet:grid-cols-2 @tablet:items-center grid gap-8">
        <div class="grid gap-4">
          <h2 class="text-[2rem] leading-tight font-semibold">{{ data.heading }}</h2>
          <p v-if="hasText" class="text-muted">{{ data.text }}</p>
          <div v-if="buttonHref && button?.label">
            <Button variant="primary" :href="buttonHref" :as="buttonAs" :label="button.label" />
          </div>
        </div>
        <UiImage
          v-if="data.image"
          :src="data.image.url"
          :alt="data.image.altText ?? ''"
          :framing="data.image.framing"
          :entry-id="entryId"
          field-path="image"
          aspect="4/3"
          rounded="xl"
        />
      </div>
    </Container>
  </Section>
</template>

What is going on:

  • useBlockData gives you the typed field values as data.
  • useEldraLink() turns the link field into an href and a label. A link whose target is gone has no href, so the button is hidden.
  • entryId and field-path let the merchant crop the image right in the page builder.
  • With no image, the block still renders a clean text column. That is what a new block looks like.

Run pnpm storybook to see it. Run pnpm previews to make its preview.png.

Field types ​

These are the field types a block.json can declare:

TypeWhat the merchant seesWhat Block.vue receives
stringOne line of plain text, up to 255 charactersstring
textPlain text of any lengthstring
rich-textA text editor with headings, lists, links and boldRichTextNode; render it with EldraRichText
markdownFormatted text stored as one Markdown stringstring; you render the Markdown
intA whole numbernumber
floatA decimal numbernumber
boolA yes/no toggleboolean
selectA choice from metadata.optionsA union of the option strings
datetimeA date and timestring
mediaAn image pickerEldraMedia (url, altText, width, height, framing)
linkA destination: product, collection, category, entry, page or URLEldraLink; resolve it with useEldraLink()
referenceA picker for products, collections or tagged entriesEldraCollectionReference for collections only, else an untyped object
listRepeatable rows of the field in metadata.itemAn array of that field's type
compositeA group of child fields from metadata.fieldsAn object; typed field by field inside a list
tabler-iconAn icon from the Tabler setThe icon name, a string
lucide-iconAn icon from the Lucide setThe icon name, a string

A media field with "multiple": true arrives as an EldraMedia[]. A reference field also needs a relation saying what may be picked: allowCollections, allowProducts or allowedTagIds.

The platform also has color, json, seo, slug, styling and uuid. The starter uses none of them in a block.

A list of links, as a header or footer uses, is a list whose item is a link field. See Menus.

More: Field types, and the one reference shape that is typed.

Variants ​

A variant is a different look for the same block. Declare a select field named variant:

json
{
  "fieldId": "variant",
  "name": "Variant",
  "type": "select",
  "metadata": { "options": ["centered", "with-image"] },
  "validators": { "required": true }
}

Read it in Block.vue like any field: data.value.variant ?? 'centered'. Storybook gets one story per option automatically.

A field only one variant uses can hide itself from the merchant for the others:

json
"showWhen": { "field": "variant", "in": ["with-image"] }

A hidden field keeps its value, so switching back restores what the merchant typed.

Slots ​

A slot is a place inside your block where the merchant can drop other blocks. The starter's hero lets the merchant put up to two call-to-action blocks under its heading:

json
"slots": [
  {
    "id": "actions",
    "label": "Action buttons",
    "maxItems": 2,
    "allowedBlockApiIds": ["cta"]
  }
]

In Block.vue, a slot is a named Vue slot. Its content is the fallback shown while the slot is empty:

vue
<slot name="actions">
  <Button :href="primaryHref" variant="primary">{{ data.primaryCtaLabel }}</Button>
</slot>

maxItems is between 1 and 20. Leave out allowedBlockApiIds to allow any block except this one.

More: Slots in the block contract.

Reusable components ​

A merchant can save a group of blocks, like a header, as a reusable component and place it on many pages. Editing it once changes it everywhere.

Your blocks do nothing special for this. The page renders it for you, as long as it passes reusableComponentProjection from useEldraPage() to EldraLayout. The starter's app/pages/[...slug].vue already does.

More: Reusable page components.

Changing a block that is live ​

Merchants have content stored in your fields. So a change that breaks that content needs a version bump:

  • Adding a field is free.
  • Removing a field, or changing its type, needs version raised by one. The platform keeps the old content as a read-only field, so nothing is lost.
  • Renaming a field needs the bump plus a migrations entry, so the content moves to the new name:
json
{
  "version": 2,
  "migrations": [{ "version": 2, "renames": [{ "from": "single", "to": "exclusive" }] }]
}

pnpm validate tells you when a bump is missing.

More: Block field migrations.

Rules for blocks ​

  • No Nuxt globals in a block. No useRoute, useHead, NuxtLink, $fetch or useAsyncData, and no auto-imports. Blocks also render in Storybook and tests, where Nuxt is not running.
  • Show a text value as you got it. Write {{ heading }}, not heading.toUpperCase(); style it with CSS instead. In Studio each value carries invisible markers that make it editable in place.
  • Check emptiness with stripStega(value).trim(). A plain trim() keeps those markers, so an empty field looks filled.
  • Keep media and reference fields out of mock.json. The platform refuses demo images there, and a new block should not point at one particular collection.
  • Render well with no images. A block the merchant just inserted has none.
  • Put every href through safeHref, and same-site ones through EldraRouterLink. That drops unsafe URLs and keeps the visitor's language in the path.
  • Read shop data through useStorefront(), never the SDK directly. That way the block works with demo data in Storybook and tests.

More: The block contract and Testing and accessibility gates.

Eldra