A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://github.com/uniibu/koa-nunjucks-async below:

uniibu/koa-nunjucks-async: A Nunjucks Renderer for KoaJs v2+ that uses native async/await of Nodejs

A Nunjucks Renderer Middleware for KoaJs v2+ that uses native async/await of Nodejs

A Koa Middleware that allows you to render nunjucks templates.

Why Build this if you can use other repositories that also supports Koa@2 ?

npm install --save koa-nunjucks-async
const Koa = require('koa');
const nunjucks = require('koa-nunjucks-async');
const app = new Koa();

const nunjucksOptions = {
    opts: {
        noCache: false,
        throwOnUndefined: false
    },
    filters: {
        json: x => JSON.stringify(x, null, 2),
        ucfirst: e => typeof e === 'string' && e.toLowerCase() && e[0].toUpperCase() + e.slice(1);
    },
    globals: { title: 'My Page' },
    ext: '.html'
};
// Load other middlewares...
// Load nunjucks last before routes
app.use(nunjucks('views', nunjucksOptions);

// Load your routes...

Note: The nunjucksOptions.opts object is passed directly to nunjucks module.

Available Options(optional) and their Default values.
let settings = {
    opts: {
        autoescape: true,
        throwOnUndefined: false,
        trimBlocks: false,
        lstripBlocks: false,
        watch: false,
        noCache: false
    },
    filters: {},
    globals: {},
    extensions: {},
    ext: '.html'
};

Check https://mozilla.github.io/nunjucks/api.html#configure for each of the opts description.

await ctx.render('name_of_template_file',context);
You can use it with Koa's native routing:
  const Koa = require('koa');
  const app = new Koa();

  app.use(async ctx => {
    await ctx.render('template', {
         message: 'Hello World!'
       });
  });
Or via other router middleware such as Koa-router:
const Router = require('koa-router');
const router = new Router();

router.get('/', async ctx => {
   await ctx.render('template', {
         message: 'Hello World!'
       });
});
Exposing variables other than context(ctx) by using ctx.state:
  const Koa = require('koa');
  const app = new Koa();

  app.use(async (ctx,next) => {
      ctx.state.title = "My Page";
      await next();
  })

  // the variable 'title' is now exposed to all templates unless overwritten by context.
  // So using {{ title }} will render "My Page".
  app.use(async ctx => {
    await ctx.render('template', {
         message: 'Hello World!'
       });
  });

This project is licensed under the Apache license. See the LICENSE file for more info.


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4