Guidance on displaying images from Sanity in 11ty, including a breakdown of the <https://github.com/brob/eleventy-plugin-sanity-image/blob/main/.eleventy.js|plugin-sanity-image>...
8 replies
Last updated: Feb 7, 2023
R
Hello! I’m using 11ty for my frontend and having trouble figuring out how to display the images from Sanity. The JSON that comes through does not have a URL, and I’ve read articles walking through the “image-url” npm plugin, but am still unable to get them the URL. Anyone have guidane? Thanks in advance!
Feb 6, 2023, 5:25 AM
S
Hi! You can use the plugin-sanity-image as is (or customise the implementation if you'd like) to get the URL from the JSON object in 11ty.
Feb 6, 2023, 5:43 AM
R
Hi
user T
! Thank you! I actually did try that as well but its a little over my head also. Is there anywhere that its broken down a little more? I’m a newbie dev, swimming in the deep end.
Feb 6, 2023, 5:47 AM
S
Ah, no worries, I can try to break it down a bit: 1. We create a function which will be able to convert Sanity JSON response -> image url, which is what the
urlFor
function does. (
options.client
is the Sanity client, which we use to authenticate requests)
function urlFor(source) {
return imageUrl(options.client).image(source)
}
2. The
@sanity/image-url
library exposes a few convenience methods to help image manipulation (cropping, resizing, format, etc on the fly). The simplest way of using this is defined in `imageUrlFor`:
urlFor(image).width(width).auto('format')
You can ignore the other two functions if you find them confusing, this is the minimum you will need.
As to how to use them, the repo should have examples + I would recommend reading the 11ty docs as well. (tl;dr, it's a handy way of calling a JS function from your templates)
Feb 6, 2023, 5:56 AM
R
Thank you so much for your explanation! Unfortunately I still am confused about just where to put everything and how it all works…I think I’ve let too much time pass since my bootcamp education. Do you know if Sanity will be coming out with a new v3 starter for 11ty? Maybe if I can see a woking example I can figure it out from there?
Feb 6, 2023, 3:20 PM
S
Ah, that's quite alright. You can put your shortcodes directly in
.eleventy.config.js
for now, and it should work. It might be wise to spend some more time familiarising yourself with 11ty first before coming back to the Sanity side of things. As for a V3 ready starter, perhaps
user Y
will be able to comment on an official starter, but I'm sure there will be community starters around anyways - it might be worth also asking in the 11ty Discord.
Feb 6, 2023, 3:25 PM
R
Thank you so much for the great advice that I will follow!!
Feb 6, 2023, 7:44 PM
S
Yes with the new version it will take our team more time to get starters out for frameworks, so asking in the framework channels will always be a good idea 🙂 btw. You can also try out 11ty channel and ask there!