Eleventy - Shortcode for Embedding Codepen

Eleventy - Shortcode for Embedding Codepen

Don't know what eleventy is? Before you read further, check out this amazing series of articles by Tatiana Mac to know more about eleventy and static site generators in general.

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, write the following code:

eleventyConfig.addLiquidShortcode("codepen", function (url) {

    const url_array = url.split("/");

    const profile_url_array = url_array.filter((string, index) => {
        return (index < (url_array.length - 2)) ? true : false
    })

    const username = profile_url_array[profile_url_array.length - 1];
    const user_profile = profile_url_array.join("/");
    const data_slug_hash = url_array[url_array.length - 1];

    return `<p class="codepen" data-height="600" data-default-tab="result" data-slug-hash="${data_slug_hash}" data-user="${username}" style="height: 571px; box-sizing: border-box; display: flex; align-items: center; justify-content: center; border: 2px solid; margin: 1em 0; padding: 1em;">
    <span><a href="${url}">See the pen</a> (<a href="${user_profile}">@${username}</a>) on <a href="https://codepen.io">CodePen</a>.</span>
    </p>
    <script async src="https://cpwebassets.codepen.io/assets/embed/ei.js"></script>`;
});

Shortcode: {% codepen 'url' %}

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 dynamic embed code.

Signing off.