From 0c178955ec4c6190b165d51143ec59e0b25ab0d5 Mon Sep 17 00:00:00 2001 From: Alice Gaudon Date: Wed, 28 Apr 2021 11:00:51 +0200 Subject: [PATCH] Fix svelte template replace would recursively replace --- src/frontend/SvelteViewEngine.ts | 41 +++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 6 deletions(-) diff --git a/src/frontend/SvelteViewEngine.ts b/src/frontend/SvelteViewEngine.ts index 6cd76b4..d02322a 100644 --- a/src/frontend/SvelteViewEngine.ts +++ b/src/frontend/SvelteViewEngine.ts @@ -62,7 +62,7 @@ export default class SvelteViewEngine extends ViewEngine { // Root template const templateFile = await this.resolveFileFromCanonicalName('layouts/svelte_layout.html'); - let output = await this.fileCache.get(templateFile, !config.get('view.cache')); + const rawOutput = await this.fileCache.get(templateFile, !config.get('view.cache')); // Pre-compiled parts const [ @@ -97,11 +97,40 @@ export default class SvelteViewEngine extends ViewEngine { const props = JSON.stringify(localMap); // Replaces - output = output.replace('%canonicalViewName%', canonicalViewName); - output = output.replace('%props%', props); - output = output.replace('%head%', head); - output = output.replace('%html%', html); - output = output.replace('%css%', css); + const replaces: { [key: string]: string } = { + canonicalViewName: canonicalViewName, + props: props, + head: head, + html: html, + css: css, + }; + const replaceOperations: Record = {}; + for (const entry of Object.entries(replaces)) { + const matches = rawOutput.matchAll(new RegExp(`%${entry[0]}%`, 'g')); + for (const match of matches) { + if (typeof match.index === 'number') { + replaceOperations[match.index] = { + key: `%${entry[0]}%`, + replaceValue: entry[1], + }; + } + } + } + + + let output = ''; + for (let i = 0; i < rawOutput.length; i++) { + const replaceOperation = replaceOperations[i]; + if (replaceOperation) { + output += replaceOperation.replaceValue; + i += replaceOperation.key.length - 1; + } else { + output += rawOutput[i]; + } + } callback(null, output); }