Templating the Image field
The Image field allows content writers to upload an image that can be configured with size constraints and responsive image views.
This article assumes that you have saved the document object in a variable named document as shown in the Retrieve the document object page.
Retrieve the image url
The easiest way to integrate an image is to retrieve and add the image url to image elements.
Here is an example that accesses the url from an Image field with the API ID of illustration.
const image_url = document.illustration.url;
Get an image view
It's easy to get the url for an image and any of its views. The following shows how to retrieve the image url for the main view as well as its tablet and mobile views. In this case, the Image field has an API ID of responsive_image.
const image = document.responsive_image; const mainUrl = image.url; // main image const tablet_url = image.tablet.url; // tablet const mobile_url = image.mobile.url; // mobile
Get the image Alt Text
If you added an alt text value to your image, you retrieve and apply it as shown below. Here the Image field has the API ID of featured_image.
const image = document.featured_image; const image_url = image.url; // url const image_alt = image.alt; // alt
The following shows how to retrieve the alt text for a responsive image view. Note that the alt text will be the same for all views.
const mobile_view = document.featured_image.mobile; const mobile_url = mobile_view.url; // mobile image url const mobile_alt = mobile_view.alt; // mobile image alt
Get the image Width & Height
Here's how to retrieve the main image's width or height. In this example, the Image field has the API ID of header_image.
const image = document.header_image; const image_width = image.dimensions.width; // image width const image_height = image.dimensions.height; // image height
Here is how to retrieve the width and height for a responsive image view.
const mobile_view = document.header_image.mobile; const mobile_width = mobile_view.dimensions.width; // mobile image width const mobile_height = mobile_view.dimensions.height; // mobile image height
Was this article helpful?
Can't find what you're looking for? Get in touch with us on our Community Forum.