A mojo.js plugin that adds support for nunjucks templates. The code of this plugin is a good example for learning to build new plugins with TypeScript, you're welcome to fork it.
import mojo from '@mojojs/core';
import nunjucksPlugin from 'mojo-plugin-nunjucks';
const app = mojo();
app.plugin(nunjucksPlugin);
// Render template "views/index.html.njk"
app.get('/template', async ctx => {
await ctx.render({view: 'index'});
});
// Render an inline nunjucks template
app.get('/inline', async ctx => {
await ctx.render({inline: '{{ greeting }} World!', engine: 'njk'}, {greeting: 'Hello'});
});
app.start();
To change the default engine for inline templates you can also set app.renderer.defaultEngine
to njk
. Or you can
register the template engine with a completely different name.
app.plugin(nunjucksPlugin, {name: 'foo'});
app.renderer.defaultEngine = 'foo';
You can also extend the environment with custom filters and tags.
app.renderer.engines.njk.env.addFilter('hello', name => {
return `hello ${name}`;
});
All you need is Node.js 16.0.0 (or newer).
$ npm install mojo-plugin-nunjucks
If you have any questions the documentation might not yet answer, don't hesitate to ask in the Forum, on Matrix, or IRC.