1.

What Is Koa.js Templating?

Answer»

Pug is a templating engine. Templating engines are used to remove the cluttering of our server CODE with HTML, concatenating strings wildly to existing HTML templates. Pug is a very POWERFUL templating engine which has a variety of features including filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this.

To USE Pug with koa, we need to install it,

$ npm install --save pug koa-pug
Now that pug is installed, set it as the templating engine for your app. Add the following code to your app.js file.
var koa = require('koa');
var router = require('koa-router');
var app = koa();
var Pug = require('koa-pug');
var pug = new Pug({
viewPath: './views',
basedir: './views',
app: app //Equivalent to app.use(pug)
});
var _ = router(); //Instantiate the router
app.use(_.routes()); //Use the routes defined using the router
app.listen(3000);

Now create a new directory called views. Inside that create a file called first_view.pug, and enter the following data in it.

doctype html
html
HEAD
title="Hello Pug"
body
p.greetings#people Hello Views!
To run this page, add the following ROUTE to your app:
_.get('/hello', getMessage); // Define routes
function *getMessage(){
this.render('first_view');
};

Pug is a templating engine. Templating engines are used to remove the cluttering of our server code with HTML, concatenating strings wildly to existing HTML templates. Pug is a very powerful templating engine which has a variety of features including filters, includes, inheritance, interpolation, etc. There is a lot of ground to cover on this.

To use Pug with koa, we need to install it,

$ npm install --save pug koa-pug
Now that pug is installed, set it as the templating engine for your app. Add the following code to your app.js file.
var koa = require('koa');
var router = require('koa-router');
var app = koa();
var Pug = require('koa-pug');
var pug = new Pug({
viewPath: './views',
basedir: './views',
app: app //Equivalent to app.use(pug)
});
var _ = router(); //Instantiate the router
app.use(_.routes()); //Use the routes defined using the router
app.listen(3000);

Now create a new directory called views. Inside that create a file called first_view.pug, and enter the following data in it.

doctype html
html
head
title="Hello Pug"
body
p.greetings#people Hello Views!
To run this page, add the following route to your app:
_.get('/hello', getMessage); // Define routes
function *getMessage(){
this.render('first_view');
};



Discussion

No Comment Found