পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Thursday, March 2, 2017

Koa.js - Templating

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');
};
You'll get the output as:
What pug does is convert this very simple looking markup to html. We dont need to keep track of closing our tags, no need to use class and id keywords, rather use '.' and '#' to define them. The above code first gets converted to:
<!DOCTYPE html>
<html>
    <head>
        <title>Hello Pug</title>
    </head>
    <body>
        <p class="greetings" id="people">Hello Views!</p>
    </body>
</html>
Pug is capable of doing much more than simplifying HTML markup. Lets explore some of these features of Pug.

Simple Tags

Tags are nested according to their indentation. Like in the above example, <title> was indented within the <head> tag, so it was inside it. But the <body> tag was on the same indentation, so it was a sibling of <head> tag.
We dont need to close tags, as soon as Pug encounters next tag on same or outer indentation level, it closes the tag for us.
To put text inside of a tag, we have 3 methods:
  • Space seperated:
    h1 Welcome to Pug
  • Piped text:
    div
        | To insert multiline text, 
        | You can use the pipe operator.
  • Block of text:
    div.
        But that gets tedious if you have a lot of text. 
        You can use "." at the end of tag to denote block of text. 
        To put tags inside this block, simply enter tag in a new line and 
        indent it accordingly.

Comments

Pug uses the same syntax as JavaScript(//) for creating comments. These comments are converted to the html comments(<!--comment-->). For example,
//This is a Pug comment
This comment gets converted to:
<!--This is a Pug comment-->

Attributes

To define attributes, we use a comma seperated list of attributes, in paranthesis. Class and ID attributes have special representations. The following line of code covers defining attributes, classes and id for a given html tag.
div.container.column.main#division(width="100",height="100")
This line of code, get converted to:
<div class="container column main" id="division" width="100" height="100"></div>

Passing values to templates

When we render a pug template, we can actually pass it a value from our route handler, which we can then use in our template. Create a new route handler with the following:
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 // equals to pug.use(app) and app.use(pug.middleware)
});

var _ = router(); //Instantiate the router

_.get('//dynamic_view', dynamicMessage); // Define routes

function *dynamicMessage(){
    this.render('dynamic', {
        name: "TutorialsPoint", 
        url:"https://www.tutorialspoint.com"
    });
};

app.use(_.routes()); //Use the routes defined using the router

app.listen(3000);
And create a new view file in views directory, called dynamic.pug, with the following code:
html
    head
        title= name
    body
        h1= name
        a(href= url) URL
Open localhost:3000/dynamic in your browser. You should get:
Variables in template We can also use these passed variables within text. To insert passed variables in between text of a tag, we use #{variableName} syntax. For example, in the above example, if we wanted to put Greetings from TutorialsPoint, then we could have done the following:
html
    head
        title= name
    body
        h1 Greetings from #{name}
        a(href= url) URL
This method of using values is called interpolation.

Conditionals

We can use conditional statements and looping constructs as well! Consider this practical example, if a User is logged in we would want to display "Hi, User" and if not, then we would want to show him a "Login/Sign Up" link. To acheive this, we can define a simple template like:
html
    head
        title Simple template
    body
        if(user)
            h1 Hi, #{user.name}
        else
            a(href="/sign_up") Sign Up
When we render this using our routes, if we pass an object like:
this.render('/dynamic',{user: 
    {name: "Ayush", age: "20"}
});
It'll give a message diaplaying Hi, Ayush. But if we dont pass any object or pass one with no user key, Then we will get a Sign up link.

Include and Components

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);
On going to localhost:3000/components, you should get the following output:
templating components include can also be used to include plaintext, css and JavaScript.
There are many more features of Pug. But those are out of the scope for this tutorial. You can further explore Pug at Pug.

No comments:

Post a Comment