refactor: move gallery entries into seperate data file
All checks were successful
Deploy on push / deploy (push) Has been skipped
All checks were successful
Deploy on push / deploy (push) Has been skipped
This commit is contained in:
61
scripts/render-gallery.js
Normal file
61
scripts/render-gallery.js
Normal file
@@ -0,0 +1,61 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const repoRoot = path.resolve(__dirname, "..");
|
||||
const dataPath = path.join(repoRoot, "data", "meals.json");
|
||||
const indexPath = path.join(repoRoot, "index.html");
|
||||
|
||||
const startMarker = "<!-- Generated gallery items: start -->";
|
||||
const endMarker = "<!-- Generated gallery items: end -->";
|
||||
|
||||
function escapeHtml(value) {
|
||||
return value
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/\"/g, """);
|
||||
}
|
||||
|
||||
function renderArticle(entry, eol) {
|
||||
const attrs = [`class="thumbnail"`, `href="images/fulls/${entry.id}.jpg"`];
|
||||
|
||||
if (entry.position) {
|
||||
attrs.push(`data-position="${escapeHtml(entry.position)}"`);
|
||||
}
|
||||
|
||||
return [
|
||||
"\t\t\t\t<article>",
|
||||
`\t\t\t\t\t<a ${attrs.join(" ")}><img src="images/thumbs/${entry.id}.jpg" alt="" /></a>`,
|
||||
`\t\t\t\t\t<h2>${escapeHtml(entry.title)}</h2>`,
|
||||
`\t\t\t\t\t<p>${escapeHtml(entry.description)}</p>`,
|
||||
"\t\t\t\t</article>",
|
||||
].join(eol);
|
||||
}
|
||||
|
||||
function renderGallery(entries, eol) {
|
||||
return entries.map((entry) => renderArticle(entry, eol)).join(eol);
|
||||
}
|
||||
|
||||
function main() {
|
||||
const entries = JSON.parse(fs.readFileSync(dataPath, "utf8"));
|
||||
const indexHtml = fs.readFileSync(indexPath, "utf8");
|
||||
const eol = indexHtml.includes("\r\n") ? "\r\n" : "\n";
|
||||
const galleryMarkup = renderGallery(entries, eol);
|
||||
const replacement = [
|
||||
`\t\t\t\t${startMarker}`,
|
||||
galleryMarkup,
|
||||
`\t\t\t\t${endMarker}`,
|
||||
].join(eol);
|
||||
|
||||
const markerPattern = new RegExp(
|
||||
`^[\\t ]*${startMarker}[\\s\\S]*?^[\\t ]*${endMarker}`,
|
||||
"m"
|
||||
);
|
||||
|
||||
if (!markerPattern.test(indexHtml)) {
|
||||
throw new Error("Could not find gallery markers in index.html");
|
||||
}
|
||||
|
||||
fs.writeFileSync(indexPath, indexHtml.replace(markerPattern, replacement));
|
||||
}
|
||||
|
||||
main();
|
||||
Reference in New Issue
Block a user