Skip to content

Commit 02e6418

Browse files
committed
🎨 refactor template RegEx; fix issue with leading space in sections
1 parent 9f9e33b commit 02e6418

File tree

2 files changed

+29
-13
lines changed

2 files changed

+29
-13
lines changed

__tests__/index.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -172,12 +172,12 @@ test('renders lists of objects', t => {
172172
}),
173173
`
174174
<ul>
175-
<li>Blake</li>
175+
<li>Blake</li>
176176
<li>Dash</li>
177177
</ul>`
178178
);
179179

180-
t.is(render(template, { people: [] }), '\n<ul>\n \n</ul>');
180+
t.is(render(template, { people: [] }), '\n<ul>\n\n</ul>');
181181
});
182182

183183
test('renders array', t => {
@@ -194,7 +194,7 @@ test('renders array', t => {
194194
}),
195195
`
196196
<ul>
197-
<li>Blake</li>
197+
<li>Blake</li>
198198
<li>Dash</li>
199199
</ul>`
200200
);

src/index.ts

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -25,18 +25,34 @@ export async function renderGlob(
2525
}
2626
}
2727

28-
const tagRegEx = /\{\{\s*(.*?)\s*\}\}/g;
29-
const sectionRegEx = /\{\{\s*(?:#(.*?))\s*\}\}\n*([\s\S]*?)\s*\{\{\s*\/\1\s*\}\}/g;
30-
const combinedRegEx = new RegExp(
31-
`${sectionRegEx.source}|${tagRegEx.source}`,
32-
'g'
33-
);
28+
function getTemplateRegEx() {
29+
const anything = '([\\s\\S]*?)';
30+
const optionalNewLines = '\\n*';
31+
const optionalWhitespace = '\\s*';
32+
const spaceNotNewLines = `[ \t]*`;
33+
34+
const tagStart = `{{${optionalWhitespace}`;
35+
const tagEnd = `${optionalWhitespace}}}`;
36+
const sectionStart = `${spaceNotNewLines}${tagStart}(?:#(.*?))${tagEnd}${optionalNewLines}`;
37+
const sectionEnd = `${optionalWhitespace}${tagStart}\\/\\1${tagEnd}`;
38+
39+
const repeatingSectionTag = `${sectionStart}${anything}${sectionEnd}`;
40+
const replacementTag = `${tagStart}(.*?)${tagEnd}`;
41+
const combinedRegEx = new RegExp(
42+
`${repeatingSectionTag}|${replacementTag}`,
43+
'g'
44+
);
45+
46+
return combinedRegEx;
47+
}
3448

3549
export function render(template: string, data: Data): string {
50+
const templateRegEx = getTemplateRegEx();
51+
3652
return template.replace(
37-
combinedRegEx,
38-
(_match, sectionTag, sectionContents, basicTag) => {
39-
// Tag is for an array section
53+
templateRegEx,
54+
(_match, sectionTag, sectionContents, replacementTag) => {
55+
// Tag is for a repeating section
4056
if (sectionTag !== undefined) {
4157
const replacements = get(sectionTag, data);
4258

@@ -47,7 +63,7 @@ export function render(template: string, data: Data): string {
4763
.join('\n');
4864
}
4965

50-
const replacement = get(basicTag, data);
66+
const replacement = get(replacementTag, data);
5167

5268
// If a template variable is found but nothing is supplied to fill it, remove it
5369
if (replacement === null || replacement === undefined) {

0 commit comments

Comments
 (0)