1.

What Is Include And Components?

Answer»

Pug provides a very intuitive way to create components for a web page. For example, if you see a news website, the header with logo and categories is always fixed. Instead of copying that to evey view we create we can use an include. Following example shows how we can use an include:

Create 3 views with the following code:

HEADER.PUG

div.header.

I'm the header for this website.

CONTENT.PUG

html
head
title Simple template
body
include ./header.pug
h3 I'm the main content
include ./footer.pug

FOOTER.PUG

div.footer.

I'm the footer for this website.

Create a route for this as follows:

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
_.get('/components', getComponents);
function *getComponents(){
this.render('content.pug');
}
app.use(_.routes()); //Use the routes DEFINED using the router
app.listen(3000);

Pug provides a very intuitive way to create components for a web page. For example, if you see a news website, the header with logo and categories is always fixed. Instead of copying that to evey view we create we can use an include. Following example shows how we can use an include:

Create 3 views with the following code:

HEADER.PUG

div.header.

I'm the header for this website.

CONTENT.PUG

html
head
title Simple template
body
include ./header.pug
h3 I'm the main content
include ./footer.pug

FOOTER.PUG

div.footer.

I'm the footer for this website.

Create a route for this as follows:

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
_.get('/components', getComponents);
function *getComponents(){
this.render('content.pug');
}
app.use(_.routes()); //Use the routes defined using the router
app.listen(3000);



Discussion

No Comment Found