Skip to content

Instantly share code, notes, and snippets.

@freshyill
Last active April 13, 2022 14:38
Show Gist options
  • Save freshyill/7c80d68310b610683b69f4c384958971 to your computer and use it in GitHub Desktop.
Save freshyill/7c80d68310b610683b69f4c384958971 to your computer and use it in GitHub Desktop.
YouTube Editor component for Netlify CMS
module.exports = function(eleventyConfig) { // This only happens once in your template!
// Blah blah, whatever other Eleventy stuff you need.
eleventyConfig.addLiquidShortcode("youtube", (youtubeId, aspectRatio) => {
return `<div class="aspect-ratio" style="--aspect-ratio: ${aspectRatio}"><iframe class="youtube-player video video--youtube" src="https://www.youtube.com/embed/${youtubeId}/" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>`;
});
// Blah blah, whatever other Eleventy stuff you need.
}; // This only happens once in your template!
CMS.registerEditorComponent({
// Internal id of the component
id: "youtube",
// Visible label
label: "Youtube",
// Fields the user need to fill out when adding an instance of the component
fields: [
{name: 'id', label: 'YouTube ID', widget: 'string'},
{name: 'aspect_ratio', label: 'Aspect ratio', widget: 'select', multiple: false, options: [ "16/9", "4/3", "1/1" ], default: "16/9"}
],
// Pattern to identify a block as being an instance of this component
pattern: /^{% youtube \"(\S+)\", \"(\S+)\" %}$/,
// Function to extract data elements from the regexp match
fromBlock: function(match) {
return {
id: match[1]
};
},
// Function to create a text block from an instance of this component
toBlock: function(obj) {
return `{% youtube "${obj.id}", "${obj.aspect_ratio}" %}`;
},
// Preview output for this component. Can either be a string or a React component
// (component gives better render performance)
toPreview: function(obj) {
return (
'<img src="http://img.youtube.com/vi/' + obj.id + '/maxresdefault.jpg#block" alt="Youtube Video"/>'
);
}
});
@rolandtoth
Copy link

Thanks, it was a very handy starting point to me.

For anyone who's using this, make sure to add this after line 16 to persist the aspect ratio:

        aspect_ratio: match[2]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment