✨Discover storytelling in the AI age with Pixar's Matthew Luhn at Sanity Connect, May 8th—register now

Embedding annotated images in blog posts using common set of images

6 replies
Last updated: Apr 9, 2021
Hi, I was what was the best way to embed a model containing an image in a block.
I want the image model to just be more than just an image and to also include a caption field. The use case is that I would like multiple blog posts with blocks as the body to be able to use a common set of images that are annotated with information such as the caption.

I tried using a reference as one of the additional types for blockContent:


{
  type: 'reference',
  to: [{type: 'photo'}]
}
where photo has the schema:


export default {
name: 'photo',
title: 'Photo',
type: 'document',
fields: [
{
name: 'title',
title: 'Title',
type: 'string'
},
{
name: 'caption',
title: 'Caption',
type: 'string',
options: {
isHighlighted: true,
}
},
]
};
But then I'm not sure how to access the actual image in the serializer for
<BlockContent/>
. I just get something like this
{_key: "3b620e4adf9d", _ref: "e8f707b7-5194-4f97-9a7d-f7deefabc069", _type: "reference"}

I also tried to adding photo as a type but then it embeds the photo in the blockContent and I can't access it from another blockContent in a different blog post.
Mar 31, 2021, 6:42 AM
When you query for the block content, you should expand the reference. Say your block content field is
body
and you have a custom block
my_photo_block
with a
photo
field:
*[_type == 'post'][0] {
  body[] {
    ...,
    _type == 'my_photo_block' => {
      photo->
    }
  }
}
…or something like that, not sure how you set up your schema
Mar 31, 2021, 7:18 AM
user G
The idea makes a lot of sense! However, after a bit of fiddling, I'm not able to get the syntax right.
Within
blockContent
I put
    {
      title: 'photo',
      type: 'reference',
      to: [{type: 'photo'}]
Then I try using this query:


   `*[_type == "post" && slug.current==$slug][0]{body[]{..., _type=='reference' => {photo->}}, title}
`,
I'm not able to get the photo yet
Mar 31, 2021, 8:08 AM
Hey!
_type
should be the name of your custom block, but it’s reference right now
Mar 31, 2021, 8:10 AM
user G
I tried
*[_type == "post" && slug.current==$slug][0]{body[]{..., _type=='photo' => {photo->}}, title}
but that also doesn't give me the results I expected.
I definitely think this is the right direction though!
Mar 31, 2021, 8:17 AM
I'm bumping this thread because I also struggle to get this right. The article in the docs isn't really helpful...
Apr 9, 2021, 1:45 PM
Derek helped me figure out a query that worked for me
*[_type == "post" && slug.current==$slug'][0]{body[]{..., _type=='reference' => {"photo":@->}}, title}
Apr 9, 2021, 2:37 PM

Sanity– build remarkable experiences at scale

Sanity is a modern headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.

Was this answer helpful?