Skip to content

Commit 5a169c7

Browse files
committed
Allow customizing the way JSON-LD data is injected into pages
1 parent e233f65 commit 5a169c7

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@ and this project try to adheres to [Semantic Versioning](https://semver.org/).
66
Go to the `v2` branch to see the changelog of Lume 2.
77
Go to the `v1` branch to see the changelog of Lume 1.
88

9+
## Unreleased
10+
### Added
11+
- `json_ld` plugin: allow customizing they way JSON-LD data is used inside pages
12+
913
## [3.2.1] - 2026-02-10
1014
### Fixed
1115
- LumeCMS: the preview url wasn't detected.

plugins/json_ld.ts

Lines changed: 26 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -170,11 +170,35 @@ function isEmpty(v: unknown) {
170170
return v === undefined || v === null || v === "";
171171
}
172172

173+
export interface Options {
174+
/**
175+
* The function executed on each HTML page file to inject the JSON-LD
176+
* data into the document. It receives the Page object and the assembled
177+
* JSON-LD string as its arguments.
178+
*
179+
* By default a <script> tag with the data is inserted into <head>.
180+
*/
181+
renderFn: (page: Page, jsonLdData: string) => void;
182+
}
183+
184+
export const defaults: Options = {
185+
renderFn: (page, jsonLdData) => {
186+
const { document } = page;
187+
const script = document.createElement("script");
188+
script.setAttribute("type", "application/ld+json");
189+
script.textContent = jsonLdData;
190+
document.head.appendChild(script);
191+
document.head.appendChild(document.createTextNode("\n"));
192+
},
193+
};
194+
173195
/**
174196
* A plugin to insert structured JSON-LD data for SEO and social media
175197
* @see https://lume.land/plugins/json_ld/
176198
*/
177-
export function jsonLd() {
199+
export function jsonLd(userOptions?: Options) {
200+
const options = Object.assign({}, defaults, userOptions || {});
201+
178202
return (site: Site) => {
179203
site.mergeKey("jsonLd", "object");
180204
site.process([".html"], function processJsonLd(pages) {
@@ -235,11 +259,7 @@ export function jsonLd() {
235259
if (jsonLdData["@context"] === undefined) {
236260
jsonLdData["@context"] = "https://schema.org";
237261
}
238-
const script = document.createElement("script");
239-
script.setAttribute("type", "application/ld+json");
240-
script.textContent = JSON.stringify(jsonLdData);
241-
document.head.appendChild(script);
242-
document.head.appendChild(document.createTextNode("\n"));
262+
options.renderFn(page, JSON.stringify(jsonLdData));
243263
}
244264
}
245265
};

0 commit comments

Comments
 (0)