nuxt-modules / sanity

Sanity integration for Nuxt
https://sanity.nuxtjs.org
MIT License
223 stars 33 forks source link

Add serializer to block to handle Images from sanity #400

Open safejace opened 2 years ago

safejace commented 2 years ago

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

wojtekpiskorz commented 1 year ago

@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

safejace commented 1 year ago

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>
wojtekpiskorz commented 1 year ago

@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

safejace commented 1 year ago

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.