sanity icon indicating copy to clipboard operation
sanity copied to clipboard

Add serializer to block to handle Images from sanity

Open safejace opened this issue 2 years ago • 4 comments

Describe the solution you'd like to see

The SanityContent component should be able to render images from sanity

Describe alternatives you've considered

Currently i solved it by adding custom serializer

safejace avatar May 16 '22 22:05 safejace

@safejace would you mind explaining a bit how you were able to do so? I'm trying for SanityContent to work with images in body but I still have only an empty tag

wojtekpiskorz avatar Feb 21 '23 21:02 wojtekpiskorz

hmmm i don't see it in my code right now, but it would look something like this:

CmsContent.vue

<script setup lang="ts">

const serializers = {
  types: {
    myImage: resolveComponent('myImage'),
  },
}
</script>

<template>
  <div v-bind="$attrs" class="cms-content">
      <SanityContent :blocks="blocks" :serializers="serializers" />
  </div>
</template>

MyImage.vue

<script setup lang="ts">
const props = defineProps<{
  src: {
    asset: {
      _ref: string
    }
  }
  alt?: string
  width?: number
  height?: number
}>()
</script>

<template>
  <nuxt-img provider="sanity" :src="props.src.asset._ref" :alt="props.alt" />
</template>

safejace avatar Feb 21 '23 22:02 safejace

@safejace Thanks for a quick response :). But the sanitizer like that doesn't work. I'm also not sure exactly how it works. so the sanitizer props should detect the root tag of the provided component and if it's an img it would replace all images inside conted with the provided component?

I do have

  sanity: {
    projectId: 'xxx'
  },
  image: {
    sanity: {
      projectId: 'xxx',
      // Defaults to 'production'
      // dataset: 'development'
    }
  },

In my nuxt.config.ts

wojtekpiskorz avatar Feb 22 '23 09:02 wojtekpiskorz

not sure if it was a typo... but you are saying sanitizer.... it's a serializer

from the module doc: https://sanity.nuxtjs.org/helpers/portable-text#example-with-custom-serializers

the [serializer] props should detect the root tag of the provided component and if it's an img it would replace all images inside conted with the provided component?

that sounds correct.

the <SanityContent> component doesn't know how to render the image. you need to pass in a component that does know.

safejace avatar Feb 22 '23 16:02 safejace