Eleventy — Shortcode for Embedding Codepen

thumbnail

Shortcodes are used to invoke a particular function which returns some html or any other data based on the information that is passed. They are mainly used to reuse html templates which require some preprocessing.

While writing blogs, I came across the need to embed codepens in my articles for a quick code demo.

Initially, I used to copy and paste the embed code provided by the codepen website. That’s not at all feasible.

It wasn’t the case that I didn’t knew about shortcodes at all because I used them on DEV, but I wasn’t sure if something like that existed in eleventy too. So, I buckled up and went on to explore shortcodes in eleventy!

Tutorial

As per eleventy’s official documentation, the default templating engine for markdown files is liquid, so here I have used a liquid shortcode as an example. You can create a shortcode for other templating engines also.

Inside .eleventy.js file, write the following code in module.exports function:

Shortcode: {% codepen 'url' %}

Place the above shortcode where you want your codepen to be embedded.

Pass a codepen url to the shortcode function. Split the url using / as a separator.

You will get an array from which you can filter out the slug after the profile url. Convert the filtered array into a string using join(""). What you get is the profile url of a codepen user.

Similarly, you can extract the username as well as the codepen id.

Copy the embed code from codepen and edit it to make it dynamic. The function returns the embed code and it is embedded inside your html template.

Signing off.

Originally published at https://syntackle.live on June 7, 2022.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Murtuza

Murtuza

Full Stack Developer | Content Creator | Technical Writer