Templating Images

Here you'll learn how to best template your images when using Gatsby and Prismic.


🕙 Before Reading

This article assumes that you have queried your API and saved the document object in a variable named document.

If this isn't the case, learn how to Retrieve the response here.

Template Images

In Prismic, you can define an image's alt text, copyright, and alternate crops — all of which can also have their own alt text. All of this information is served in the API. A simple image field response might look like this:

Copy
"example_image": {
  url
  alt
  copyright
  dimensions {
    height
    width
  }
  thumbnails {
    mobile {
      url
      alt
    }
    tablet {
      url
      alt
    }
  }
}

You can template images as normal using an img tag, or a picture tag if you have multiple responsive views:

  • <img/>
  • <picture/>
Copy
<img src={document.example_image.url} alt={document.example_image.alt} />
Copy
<picture>
   <source
     srcSet={document.example_image.thumbnails.mobile.url : ''}
     alt={document.example_image.thumbnails.mobile.alt : ''}
     media="(max-width: 500px)"
   />
   <source
     srcSet={document.example_image.thumbnails.tablet.url : ''}
     alt={document.example_image.thumbnails.tablet.alt : ''}
     media="(max-width: 1100px)"
   />
   <img
     src={document.example_image.url : ''}
     alt={document.example_image.alt : ''}
   />
</picture>

Imgix Optimization and gatsby-Image

The gatsby-source-prismic plugin supports gatsby-image using Imgix or react-imgix for image fields. Imgix + Prismic optimizes your images and delivers them in the best format based on the end-users browser through our API.

The best part is that we pay all the processing costs of using this powerful image tool for you, so you'll save money on build time costs! 😃

Image Transformations

You can set your image sizes and do cropping of your images from the Prismic document editor. If you want to make any processing changes, you can edit the URL string coming from the API.

For example, if you return your URL string in your project as a variable called img, then you can remove the auto compression by adding a parameter to this string to set the quality to 100% of maximum. Here's what that would look like:

Copy
const newUrl =`${img}&q=100`

Interesting reads: