Skip to content

Commit

Permalink
Fix issues with persist tags (fix #301)
Browse files Browse the repository at this point in the history
  • Loading branch information
mgmeyers committed Oct 22, 2023
1 parent 2071746 commit d76155b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/bbt/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -380,7 +380,7 @@ export async function renderTemplates(
template,
templateData
);
hasPersist = PersistExtension.re.test(main);
hasPersist = PersistExtension.hasPersist(main);
} catch (e) {
if (shouldThrow) {
throw errorToHelpfulError(
Expand Down
11 changes: 8 additions & 3 deletions src/bbt/template.env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,21 +174,26 @@ export class PersistExtension implements Extension {
retained = context.ctx._retained[id];
}

const trimmed = (body() as string).replace(/^\r?\n/, '');
let trimmed = body() as string;
if (retained) trimmed = trimmed.trimStart();

return new nunjucks.runtime.SafeString(
`%% begin ${id} %%${retained}${trimmed}%% end ${id} %%`
);
}

static re = /%% begin (.+?) %%([\w\W]*?)%% end \1 %%/gi;
static hasPersist(str: string) {
this.re.lastIndex = 0;
return this.re.test(str);
}
static prepareTemplateData<T>(templateData: T, md: string): T & WithRetained {
const out: Record<string, string> = {};

if (!md) return templateData;

const matches = md.matchAll(this.re);
for (const match of matches) {
this.re.lastIndex = 0;
for (const match of md.matchAll(this.re)) {
out[match[1]] = match[2];
}

Expand Down

0 comments on commit d76155b

Please sign in to comment.