Using Nunjucks to generate Open Graph images #581
-
The OG images plugin is excellent. So firstly, thanks for providing this! However, I'd like to use Nunjucks to generate Open Graph images, rather than learn Satori's JSX syntax. I'm already using Nunjucks everywhere else I'm working with a layout, so I'd prefer to stick with this templating engine. I had a go at copying the OG Images pluging and replacing the Satori calls with Nunjucks. However, I'm not sure how to go about using the Nunjucks environment that's already been set up by the Nunjucks plugin (or how to create a new, equivalent environment). Taking the The OG images plugin as a starting point, this is part of the change that I've got so far: async function render(
- jsx: React.ReactNode,
+ template: string,
+ data?: Record<string, unknown>
): Promise<Uint8Array | undefined> {
if (cache) {
- const result = await cache.get(new Uint8Array(), jsx);
+ const result = await cache.get(new Uint8Array(), template);
if (result) {
return result;
}
}
- const svg = await satori(jsx, options.satori);
+ // TODO how to reuse or create an environment here?
+ const env = new nunjucks.Environment();
+
+ const engine = new NunjucksEngine(env, site.src(), options.includes);
+ const svg = await engine.render(template, data);
const content = await (await create(svg)).toBuffer()
if (cache) {
- await cache.set(new Uint8Array(), jsx, content);
+ await cache.set(new Uint8Array(), template, content);
}
return content;
} Now, this seems to work, until I try and use certain filters. For example, using trying to use the
How can I reuse the environment set up by the Nunjucks plugin when trying to use Nunjucks to generate Open Graph images? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The advantage of Satori is it can output SVG using simple CSS and HTML, which is easier than generating the SVG code using a text-based engine like Nunjucks. But maybe this plugins should allow both options. I'll work on that for next versions. const format = site.formats.search(".njk"); // Get the configuration for the .njk file extension
const env = format.engines[0]; // Get the engine for Nunjucks |
Beta Was this translation helpful? Give feedback.
The advantage of Satori is it can output SVG using simple CSS and HTML, which is easier than generating the SVG code using a text-based engine like Nunjucks. But maybe this plugins should allow both options. I'll work on that for next versions.
Meanwhile, you can reuse the existing nunjucks environment: