পৃষ্ঠাসমূহ

.

Search Your Article

Total Pageviews

Friday, February 17, 2017

ExpressJS - Templating

Pug is a templating engine for express. 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 express, we need to install it,
npm install --save pug
Now that pug is installed, set it as the templating engine for your app. You don't need to 'require' it. Add the following code to your index.js file.
app.set('view engine', 'pug');
app.set('views','./views');
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 World!
To run this page, add the following route to your app:
app.get('/first_template', function(req, res){
    res.render('first_view');
});
You'll get the output as Hello World! 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 World!</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 express = require('express');
var app = express();

app.get('/dynamic_view', function(req, res){
    res.render('dynamic', {
        name: "TutorialsPoint", 
        url:"http://www.tutorialspoint.com"
    });
});

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. The output for the above code is:

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:
res.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 express = require('express');
var app = express();

app.get('/components', function(req, res){
    res.render('content');
});

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