Fix svelte template replace would recursively replace

This commit is contained in:
Alice Gaudon 2021-04-28 11:00:51 +02:00
parent 98008517b2
commit 0c178955ec

View File

@ -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<boolean>('view.cache'));
const rawOutput = await this.fileCache.get(templateFile, !config.get<boolean>('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<number, {
key: string;
replaceValue: string;
} | undefined> = {};
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);
}