diff --git a/runtime/src/server/middleware/get_page_handler.ts b/runtime/src/server/middleware/get_page_handler.ts index 53f413640..32cd6e93d 100644 --- a/runtime/src/server/middleware/get_page_handler.ts +++ b/runtime/src/server/middleware/get_page_handler.ts @@ -320,12 +320,14 @@ export function get_page_handler( // users can set a CSP nonce using res.locals.nonce const nonce_attr = (res.locals && res.locals.nonce) ? ` nonce="${res.locals.nonce}"` : ''; - const body = template() - .replace('%sapper.base%', () => ``) - .replace('%sapper.scripts%', () => `${script}`) - .replace('%sapper.html%', () => html) - .replace('%sapper.head%', () => `${head}`) - .replace('%sapper.styles%', () => styles); + const body = replace(template(), { + ...res.replacers, + base: () => ``, + scripts: () => `${script}`, + html: () => html, + head: () => `${head}`, + styles: () => styles + }); res.statusCode = status; res.end(body); @@ -356,6 +358,18 @@ export function get_page_handler( }; } +function replace( + template: string, + replacers: Record +) { + for (const key in replacers) { + if (replacers.hasOwnProperty(key)) { + template = template.replace(new RegExp(`%sapper.${key}%`, 'g'), replacers[key] as any); + } + } + return template; +} + function read_template(dir = build_dir) { return fs.readFileSync(`${dir}/template.html`, 'utf-8'); }