I write a website using koajs and ejs template engine, I found I need to render a same year when access different route, like this:
router.get('/', async (ctx, next) => {
await ctx.render('index', {
currentYear: templates.currentYear, // <--this line will repeat many times
sub_title: 'Index',
}));
}).get('/notfound', async (ctx, next) => {
await ctx.render('404', {
sub_title: 'Not Found',
currentYear: templates.currentYear, // <--this line will repeat many times
});
})
can I get rid of it? I tried this way:
const templatesObject = {
currentYear: new Date().getFullYear(),
}
// use a addTemplate function to merge the template object
const addTemplate = (obj) => {return {...templatesObject, ...obj}}
// index
router.get('/', async (ctx, next) => {
await ctx.render('index', addTemplate({
sub_title: 'Index', // <-- now I need not to write currentYear many times
}));
})
but I wonder if I can have better way to solve it? PS: the current year may be an example, it can be a website name, a user information, etc.