Skip to content

Commit

Permalink
🎨 refactor template RegEx; fix issue with leading space in sections
Browse files Browse the repository at this point in the history
  • Loading branch information
blakek committed Jan 20, 2021
1 parent 9f9e33b commit 02e6418
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 13 deletions.
6 changes: 3 additions & 3 deletions __tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -172,12 +172,12 @@ test('renders lists of objects', t => {
}),
`
<ul>
<li>Blake</li>
<li>Blake</li>
<li>Dash</li>
</ul>`
);

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

test('renders array', t => {
Expand All @@ -194,7 +194,7 @@ test('renders array', t => {
}),
`
<ul>
<li>Blake</li>
<li>Blake</li>
<li>Dash</li>
</ul>`
);
Expand Down
36 changes: 26 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,34 @@ export async function renderGlob(
}
}

const tagRegEx = /\{\{\s*(.*?)\s*\}\}/g;
const sectionRegEx = /\{\{\s*(?:#(.*?))\s*\}\}\n*([\s\S]*?)\s*\{\{\s*\/\1\s*\}\}/g;
const combinedRegEx = new RegExp(
`${sectionRegEx.source}|${tagRegEx.source}`,
'g'
);
function getTemplateRegEx() {
const anything = '([\\s\\S]*?)';
const optionalNewLines = '\\n*';
const optionalWhitespace = '\\s*';
const spaceNotNewLines = `[ \t]*`;

const tagStart = `{{${optionalWhitespace}`;
const tagEnd = `${optionalWhitespace}}}`;
const sectionStart = `${spaceNotNewLines}${tagStart}(?:#(.*?))${tagEnd}${optionalNewLines}`;
const sectionEnd = `${optionalWhitespace}${tagStart}\\/\\1${tagEnd}`;

const repeatingSectionTag = `${sectionStart}${anything}${sectionEnd}`;
const replacementTag = `${tagStart}(.*?)${tagEnd}`;
const combinedRegEx = new RegExp(
`${repeatingSectionTag}|${replacementTag}`,
'g'
);

return combinedRegEx;
}

export function render(template: string, data: Data): string {
const templateRegEx = getTemplateRegEx();

return template.replace(
combinedRegEx,
(_match, sectionTag, sectionContents, basicTag) => {
// Tag is for an array section
templateRegEx,
(_match, sectionTag, sectionContents, replacementTag) => {
// Tag is for a repeating section
if (sectionTag !== undefined) {
const replacements = get(sectionTag, data);

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

const replacement = get(basicTag, data);
const replacement = get(replacementTag, data);

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

0 comments on commit 02e6418

Please sign in to comment.