Does anyone has any experience in trying to render slices in svelte/sapper ?
Paul
Does anyone has any experience in trying to render slices in svelte/sapper ?
Paul
I've just had a go (first time using Svelte actually) and it's not too hard.
Once you have your page data from Prismic (which you can use prismic-javascript
for), run the slices through an {#each}
block:
<!-- App.svelte -->
<script>
import Prismic from 'prismic-javascript'
import PrismicDOM from 'prismic-dom'
async function getPage () {
return await Prismic.api('https://your-repository.cdn.prismic.io/api/v2')
.then((api) => {
return api.getByID('XqLu6REAACfAY6IC') // Put a real document ID here
})
}
</script>
{#await getPage()}
<p>Loading...</p>
{:then prismic}
{#each prismic.data.body as slice}
{#if slice.slice_type === 'text'}
{@html PrismicDOM.RichText.asHtml(slice.primary.text)}
{:else if slice.slice_type === 'image_link_grid'}
{#each slice.items as image}
<img src="{image.image.url}">
{/each}
<!-- Add more slice things here by checking the slice_type -->
{/if}
{/each}
{:catch}
<p>Error getting data</p>
{/await}
Thanks , this is very helpful , unfortunately as it stands it doesn't appear to be working in sapper, but possibly with some adjustments it will !
Best wishes,
Paul
Just tried using Sapper, and it renders:
<!-- /src/routes/[slug].svelte -->
<script context="module">
import Prismic from 'prismic-javascript'
import PrismicDOM from 'prismic-dom'
export async function preload (page, session) {
const { slug } = page.params
console.log(slug)
const api = await Prismic.api('https://your-repo.cdn.prismic.io/api/v2')
const document = await api.getByUID('page', slug)
return { document }
}
</script>
<script>
export let document
</script>
<div>
{#each document.data.body as slice}
{@html PrismicDOM.RichText.asHtml(slice.primary.title)}
{/each}
</div>
I'm not sure I'm using it correctly, I haven't touched the server or anything. This is a proof of concept, and it seems to be okay.
This issue has been closed due to inactivity. Flag to reopen.
FYI, With SvelteKit in beta currently, we've published a tutorial on using Prismic with SvelteKit:
https://prismic.io/blog/svelte-sveltekit-tutorial
We don't have any documentation for implementing previews, yet, but that will be forthcoming.