Home > OS >  Sanity do not render images from body
Sanity do not render images from body

Time:07-02

This is my code. Everything renders except images. How to get images in the right order from body? I'm using sanity-blocks-vue-component to render body block. While fetching query Im also fetching body from it.

export default {
  name: 'SinglePost',
  components: { SanityBlocks },
  data() {
    return {
      loading: true,
      post: [],
      blocks: [],
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    imageUrlFor(source) {
      return imageBuilder.image(source);
    },
    fetchData() {
      this.error = this.post = null;
      this.loading = true;

      sanity.fetch(query, { slug: this.$route.params.slug }).then(
        (post) => {
          this.loading = false;
          this.post = post;
          this.blocks = post.body;
        },
        (error) => {
          this.error = error;
        }
      );
    },
  },
};

Template:

<SanityBlocks :blocks="blocks" />

post.js in sanity folder

    {
  name: 'body',
  title: 'Body',
  type: 'blockContent',
},

CodePudding user response:

You need to serialize the image. Change the template to

<SanityBlocks :blocks="blocks" :serializers="serializers" />

and then add the serializer code:

const serializers = {
  types: {
    image: (data) => {
      return h("img", { src: imageUrlFor(data).width(400).url() });
    },
  },
};

Remember to export this along with the blocks.

You can grab the h component from vue:

import { h } from "vue";
  • Related