GithubHelp home page GithubHelp logo

kiwikilian / eleventy-plugin-og-image Goto Github PK

View Code? Open in Web Editor NEW
45.0 2.0 3.0 2.07 MB

Create Open Graph images in Eleventy using your templates, data and CSS. Fast and reproducible, without a headless browser.

License: MIT License

JavaScript 86.81% Nunjucks 13.19%
eleventy eleventy-plugin

eleventy-plugin-og-image's Introduction

Eleventy Plugin OG Image npm

This plugin helps to create Open Graph images in Eleventy using a template language of your choice12 and CSS3 via satori. No headless browser will be harmed 😉.

Usage

Note

This is the documentation for eleventy-plugin-og-image ^2.0.0. If your project already uses @11ty/eleventy >=3.0.0-alpha.1 and switched to ESM it's recommended to use the current beta of this plugin.

Install the package:

npm install eleventy-plugin-og-image --save-dev

Add the plugin to your .eleventy.js:

const EleventyPluginOgImage = require('eleventy-plugin-og-image');

module.exports = (eleventyConfig) => {
  eleventyConfig.addPlugin(EleventyPluginOgImage, {
    satoriOptions: {
      fonts: [
        {
          name: 'Inter',
          data: fs.readFileSync('../path/to/font-file/inter.woff'),
          weight: 700,
          style: 'normal',
        },
      ],
    },
  });
};

Create an OG-image-template, using the supported HTML elements2 and CSS properties3. CSS in <style> tags will be inlined, remote images fetched. This is an example og-image.og.njk:

<style>
    .root {
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        background: linear-gradient(135deg, #ef629f, #eecda3);
    }

    .title {
        color: white;
        font-size: 80px;
        margin: auto 0;
    }
</style>

<div class="root">
    <h1 class="title">{{ title }}</h1>
</div>

Call the ogImage shortcode inside the <head> in a template. The first argument is the filePath of the OG-image-template (required, relative to the location from where you execute the eleventy command), second argument is for data (optional). Usage example in Nunjucks, e.g. example-page.njk:

{% ogImage "./og-image.og.njk", { title: "Hello World!" } %}

Result

Generated OG image _site/og-images/s0m3h4sh.png:

Generated OG image

HTML output generated by the shortcode in _site/example-page/index.html (can be modified via the generateHTML option):

<meta property="og:image" content="/og-images/s0m3h4sh.png" />

For applied usage see the example.

Note The template language of the page and OG-image-template can be mixed and matched.1

Configuration

The following options can be passed when adding the plugin:

Property Type Default
inputFileGlob glob **/*.og.* This must match the OG-image-templates to prevent HTML compilation.
getOutputFileSlug function See source Generation of the output file slug. Return must be url safe and exclude the file extension.
outputFileExtension sharp output file formats png
outputDir string _site/og-images/ Directory into which OG images will be emitted. Relative to the location from where you execute the eleventy command. Change urlPath accordingly.
urlPath string /og-images/ URL-prefix which will be used in returned meta-tags. Change outputDir accordingly.
generateHTML function See source Change the rendered HTML in pages.
satoriOptions satori options { width: 1200, height: 630, fonts: [] } If an OG-image-template contains text, it's required to load a font (example).
sharpOptions sharp output options undefined Options must be corresponding to chosen outputFileExtension.

Development Mode

During development the OG image file name is the url slug of the page it's generated from. In production builds, a hash of the content will be used. You'll have to handle this yourself, if you pass a custom getOutputFileSlug.

Advanced Usage

Custom Shortcode

If you would like to build your own shortcode, you can directly use the renderOgImage function.

const { renderOgImage } = require('eleventy-plugin-og-image/render');

const { html, svg, pngBuffer } = await renderOgImage({ inputPath, data, satoriOptions, templateConfig });

Capture Output URL

If you don't want to directly generate HTML with the shortcode, you can modify the generateHTML option to directly return the outputUrl:

eleventyConfig.addPlugin(EleventyPluginOgImage, {
  generateHTML: (outputUrl) => outputUrl,
});

Now you can capture the outputUrl in your page, e.g. in Nunjucks:

{% setAsync "ogOutputUrl" -%}
    {% ogImage "./og-image.og.njk", { title: "Hello World!" } %}
{%- endsetAsync %}

And use it anywhere below with {{ ogOutputUrl }}.

Acknowledgements & Attributions

This plugin is deeply inspired by @vercel/og.

Furthermore, it would not be possible without:

Footnotes

  1. Handlebars doesn't support async shortcodes and therefore can't use the ogImage shortcode. Nevertheless, an OG-image-template can use Handlebars (.og.hbs). 2

  2. Only a subset of HTML elements is supported by satori. 2

  3. Only a subset of CSS properties are supported by yoga-layout, which is used by satori. 2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.