plugins/view-nunjucks/README.md
nunjucks view plugin for egg.
npm install @eggjs/view-nunjucks
Enable plugin in config/plugin.ts
import nunjucksPlugin from '@eggjs/view-nunjucks';
export default {
...nunjucksPlugin(),
};
Set mapping in config/config.default.ts
import { defineConfig } from 'egg';
export default defineConfig({
view: {
defaultViewEngine: 'nunjucks',
mapping: {
'.nj': 'nunjucks',
},
},
});
Render in controller by ctx.render
// {app_root}/app/controller/test.ts
import { Controller } from 'egg';
class TestController extends Controller {
async list() {
const ctx = this.ctx;
// ctx.body = await ctx.renderString('{{ name }}', { name: 'local' });
// not need to assign `ctx.render` to `ctx.body`
// https://github.com/mozilla/nunjucks/blob/6f3e4a36a71cfd59ddc8c1fc5dcd77b8c24d83f3/nunjucks/src/environment.js#L318
await ctx.render(
'test.nj',
{ name: 'view test' },
{
path: '***',
}
);
}
}
escape filter is replaced by helper.escape which is provided by @eggjs/security for better performanceapp/extend/filter.ts, then they will be injected automatically to nunjucks// {app_root}/app/extend/filter.ts
export const hello = (name: string) => `hi, ${name}`;
// so you could use it at template
// {app_root}/app/controller/test.ts
import { Controller } from 'egg';
class TestController extends Controller {
async list() {
const ctx = this.ctx;
ctx.body = await ctx.renderString(
'{{ name | hello }}',
{ name: 'egg' },
{
path: '***',
}
);
}
}
you can extend custom tag like this:
// {app_root}/app/extend/application.ts
import type { Application, ILifecycleBoot } from 'egg';
import markdown from 'nunjucks-markdown';
import { marked } from 'marked';
export default class AppBoot implements ILifecycleBoot {
app: Application;
constructor(app: Application) {
this.app = app;
}
async didLoad(): Promise<void> {
markdown.register(app.nunjucks, marked);
}
}
see @eggjs/security
_csrf attr to form fieldnonce attr to script taghelper/ctx/request in template, such as helper.shtml('<div></div>')helper.upper('test')helper.shtml/surl/sjs/escape is auto wrapped with safeapp.nunjucks - nunjucks environmentapp.nunjucks.cleanCache(fullPath/tplName) to easy clean cache, can use with custom @eggjs/watchersee config/config.default.ts for more details.
Please open an issue here.
Made with contributors-img.