Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creates a handlebars instance per invocation of load Templates. #435

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 51 additions & 48 deletions lib/templates.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,47 +4,6 @@ import handlebars from 'handlebars';

const dateFormatter = new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeZone: 'UTC' });

// A helper to turn a datetime into a human readable string.
handlebars.registerHelper('humanDate', stamp => dateFormatter.format(new Date(stamp)));
handlebars.registerHelper('humanDateTime', (stamp, timeZone) => {
return new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long', timeZone }).format(new Date(stamp));
});
handlebars.registerHelper('navElement', function (url, name) {
const escapedName = handlebars.escapeExpression(name);

if (url === this.localUrl) { // eslint-disable-line no-invalid-this
return escapedName;
}

const escapedUrl = handlebars.escapeExpression(url);

return new handlebars.SafeString(`<a href="${escapedUrl}">${escapedName}</a>`);
});
handlebars.registerHelper('encodeUriComponent', encodeURIComponent);

// A helper to turn a datetime into an ISO string (without milliseconds).
handlebars.registerHelper('isoDate', datetime => new Date(datetime)
.toISOString()
.replace(/\.\d{3}Z/, 'Z')
);

handlebars.registerHelper('initialUpper', string => string[0].toUpperCase() + string.slice(1));

const year = new Date().getUTCFullYear();

handlebars.registerHelper('year', () => year);

handlebars.registerHelper('hash', (field, chars) => {
return createHash('sha256')
.update(field)
.digest('hex')
.slice(0, chars);
});

handlebars.registerHelper('ifeq', function (a, b, { fn, inverse }) {
return a === b ? fn(this) : inverse(this); // eslint-disable-line no-invalid-this
});

function makePicker(list) {
let filtered = list;

Expand All @@ -58,18 +17,62 @@ function makePicker(list) {
};
}

handlebars.registerHelper('lightEmoji', makePicker(['🌴', '☀️', '🕶', '🐬', '🦜', '🍉']));
handlebars.registerHelper('darkEmoji', makePicker(['⭐️', '🌙', '🍹', '🌴', '🎷']));

async function getTemplateAndName(directory, filename) {
const source = await readFile(new URL(filename, directory), 'utf8');
const name = filename.slice(0, filename.lastIndexOf('.', filename.length - 12)); // trim off .ext.handlebars

return [name, source.trim()];
}

export default async function loadTemplates(dir, { baseTitle }) {
handlebars.registerHelper('baseTitle', () => baseTitle);
export default async function loadTemplates(dir, { baseTitle: title }) {
const fullYear = new Date().getUTCFullYear();
const bars = handlebars.create();

bars.registerHelper({
baseTitle() {
return title;
},
lightEmoji: makePicker(['🌴', '☀️', '🕶', '🐬', '🦜', '🍉']),
darkEmoji: makePicker(['⭐️', '🌙', '🍹', '🌴', '🎷']),
ifeq(a, b, { fn, inverse }) {
return a === b ? fn(this) : inverse(this); // eslint-disable-line no-invalid-this
},
hash(field, chars) {
return createHash('sha256')
.update(field)
.digest('hex')
.slice(0, chars);
},
year() {
return fullYear;
},
initialUpper(string) {
return string[0].toUpperCase() + string.slice(1);
},
isoDate(datetime) {
return new Date(datetime)
.toISOString()
.replace(/\.\d{3}Z/, 'Z');
},
encodeUriComponent: encodeURIComponent,
navElement(url, name) {
const escapedName = bars.escapeExpression(name);

if (url === this.localUrl) { // eslint-disable-line no-invalid-this
return escapedName;
}

const escapedUrl = bars.escapeExpression(url);

return new bars.SafeString(`<a href="${escapedUrl}">${escapedName}</a>`);
},
humanDateTime(stamp, timeZone) {
return new Intl.DateTimeFormat('en-GB', { dateStyle: 'full', timeStyle: 'long', timeZone }).format(new Date(stamp));
},
humanDate(stamp) {
return dateFormatter.format(new Date(stamp));
}
});

const partialsPath = new URL('partials/', dir);
const templatesPath = new URL('documents/', dir);
Expand All @@ -89,13 +92,13 @@ export default async function loadTemplates(dir, { baseTitle }) {
return Promise.all(partialFilenames.map(async n => {
const [name, source] = await getTemplateAndName(partialsPath, n);

handlebars.registerPartial(name, source);
bars.registerPartial(name, source);
}));
})
]);

for (const [name, source] of documentsSources) {
templates[name] = handlebars.compile(source);
templates[name] = bars.compile(source);
}

return templates;
Expand Down