block-content-to-markdown icon indicating copy to clipboard operation
block-content-to-markdown copied to clipboard

possible to re-use a serializer inside a custom serializer?

Open zackseuberling opened this issue 4 years ago • 1 comments

I have configured a "gallery" block with an array of image fields:

export default {
  title: "Gallery",
  name: "gallery",
  type: "object",
  fields: [
    {
      title: "Images",
      name: "galleryImages",
      type: "array",
      of: [
        {
          type: "image",
        },
      ],
    },
  ],
};

I'd like to easily be able to wrap my gallery blocks in some custom HTML, but rather than re-write the image serializer, re-use the default serializer when the block encountered is an image. is there an easy way to do this?

zackseuberling avatar Feb 11 '21 05:02 zackseuberling

I have come up with a solution, but it's not ideal:

FWIW, I am using Eleventy to render my data, which can handle a number of different templating languages.

injecting HTML into my markdown meant the markdown template rendered my code as a string, so I switched to @sanity-io/block-content-to-html. converting my blocks to HTML means I need to tell my template that my string is safe.

here's the solution I came up with

const BlocksToHtml = require("@sanity/block-content-to-html");
const h = BlocksToHtml.h;

const image = (block) => BlocksToHtml({ blocks: block, ...client.config() });

const serializers = {
  types: {
    gallery: ({ node }) => {
      return h("div", {
        className: "gallery flex w-screen",
        innerHTML: node.galleryImages.map((i) => image(i)).join(""),
      });
    },
  },
};

zackseuberling avatar Feb 11 '21 05:02 zackseuberling