Created
June 28, 2023 13:56
-
-
Save JohnRSim/9318c9806e3a733f566fd9852560d791 to your computer and use it in GitHub Desktop.
OCM retrieve srcset rendition data for picture tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Private method for adding the specified format rendition to the rendition string | |
* | |
* @param {Object} url - the url which contains the rendition strings | |
* @param {Object} rendition - the rendition field of the content sdk json object | |
* @param {String} formatstr - the format string type - either webp or jpg | |
*/ | |
function addRendition(urls, rendition, formatstr) { | |
// Get the webp format field | |
const format = rendition.formats.filter((item) => item.format === `${formatstr}`)[0]; | |
const self = format.links.filter((item) => item.rel === 'self')[0]; | |
const url = self.href; | |
const { width } = format.metadata; | |
// Also save the jpg format so that it can be used as a default value for images | |
if (formatstr === 'jpg') { | |
urls[rendition.name.toLowerCase()] = url; | |
urls.jpgSrcset += `${url} ${width}w,`; | |
} else { | |
urls.srcset += `${url} ${width}w,`; | |
} | |
} | |
/** | |
* Retrieve the sourceset for an asset that is constructed from the rendition | |
* | |
* @param {asset} client - the asset whose fields contain the various renditions | |
* @returns {Object} - An Object containing the the sourceset as well as individual rendition | |
* url that can be used as default src | |
*/ | |
function getSourceSet(asset) { | |
const urls = {}; | |
urls.srcset = ''; | |
urls.jpgSrcset = ''; | |
if (asset.fields && asset.fields.renditions) { | |
asset.fields.renditions.forEach((rendition) => { | |
addRendition(urls, rendition, 'jpg'); | |
addRendition(urls, rendition, 'webp'); | |
}); | |
} | |
// add the native rendition to the srcset as well | |
urls.srcset += `${asset.fields.native.links[0].href} ${asset.fields.metadata.width}w`; | |
urls.native = asset.fields.native.links[0].href; | |
urls.width = asset.fields.metadata.width; | |
urls.height = asset.fields.metadata.height; | |
return urls; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment