Expose typed content fields for first home blocks
This commit is contained in:
+36
-1
@@ -33,6 +33,41 @@ function escapeRegExp(value) {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
function getByPath(source, path) {
|
||||
return path.split(".").reduce((value, key) => value?.[key], source);
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
return String(value)
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">");
|
||||
}
|
||||
|
||||
function escapeAttr(value) {
|
||||
return escapeHtml(value).replaceAll('"', """).replaceAll("'", "'");
|
||||
}
|
||||
|
||||
function renderTemplateTokens(html, block) {
|
||||
return html.replace(/\{\{\s*(text|html|attr):([a-zA-Z0-9_.-]+)\s*\}\}/g, (_match, mode, path) => {
|
||||
const value = getByPath(block, path);
|
||||
|
||||
if (value === undefined) {
|
||||
throw new Error(`Missing token value "${path}" in block "${block.id}"`);
|
||||
}
|
||||
|
||||
if (mode === "html") {
|
||||
return value == null ? "" : String(value);
|
||||
}
|
||||
|
||||
if (mode === "attr") {
|
||||
return value == null ? "" : escapeAttr(value);
|
||||
}
|
||||
|
||||
return value == null ? "" : escapeHtml(value);
|
||||
});
|
||||
}
|
||||
|
||||
function scopeDuplicateIds(html, scope) {
|
||||
const ids = [...html.matchAll(/\sid="([^"]+)"/g)].map((match) => match[1]);
|
||||
if (!ids.length) {
|
||||
@@ -62,7 +97,7 @@ async function renderBlock(block, renderCounts) {
|
||||
const renderCount = renderCounts.get(templateName) ?? 0;
|
||||
renderCounts.set(templateName, renderCount + 1);
|
||||
|
||||
const html = await readTemplate(templateName);
|
||||
const html = renderTemplateTokens(await readTemplate(templateName), block);
|
||||
|
||||
if (renderCount === 0 && block.scopeIds !== true) {
|
||||
return html;
|
||||
|
||||
Reference in New Issue
Block a user