@prismicio/svelte - Alpha

Overview

@prismicio/svelte is the official Prismic package for creating web apps with Prismic and Svelte.

To learn to develop with Prismic and Svelte, see our user-friendly Svelte guide.

This package is currently in alpha. To contribute, reach out on GitHub.

Dependencies and requirements

This package can only be used in a Svelte project.

Installation

Install this package in your Svelte project:

Copy
npm install --save-dev @prismicio/svelte

Example

Here is an example in a Svelte project. The App.svelte file will import the SliceZone and use it to render Slices as Svelte components.

src/App.svelte
Copy
<script>
  import * as prismic from "@prismicio/client"
  import { SliceZone } from "@prismicio/svelte"

  // Import Slices components and map them to API IDs
  import ExampleSlice from "./slices/ExampleSlice.svelte"

  const components = {
    "example_slice_a": ExampleSlice,
  }

  // Query a document from Prismic
  const client = prismic.createClient("example-prismic-repo")
  const promise = client.getFirst()
</script>

{#await promise}
  <p>Loading Slices</p>
{:then document}
  <SliceZone 
    slices={document.data.body} 
    {components}
  />
{:catch error}
  <pre>{JSON.stringify(error.message, null, 2)}</pre>
{/await}

Each Slice component receives a slice object as a prop.

src/slices/ExampleSlice.svelte
Copy
<script>
  export let slice
</script>

<h1>{slice.primary.example_key_text_in_slice}</h1>

Usage

@prismicio/svelte exports one component: a SliceZone.

<SliceZone>

Copy
<script>
  import { SliceZone } from "@prismicio/svelte";
</script>

The SliceZone is a Svelte component that renders an array of Prismic Slices with corresponding Slice components.

Copy
<SliceZone
  slices={document.data.body}
  components={{
    example_slice_a: ExampleSliceA,
    example_slice_b: ExampleSliceB
  }}
  context={{ foo: "bar" }}
/>

The SliceZone accepts five props:

slices

array

An array of Slices from the Prismic API.

components

object

An object mapping Svelte Slice components to API IDs.

context

object

Arbitrary data to pass to Slice components.

defaultComponent

object

The component that the SliceZone will render when a component cannot be found for a Slice. Receives the slice object and the dev property as props. A built-in default component will be rendered if none is provided. The built-in component will render nothing if dev is false.

dev

boolean

Should specify whether the application is in development (true) or production (false).


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Spot an error in the documentation? Get in touch with us on our Community Forum or using the feedback form above.