Monday 14 August 2017

Node Js - emplate Engines: Jade and Handlebars

  • Jade Syntax and Features
Normal HTML::

<body>
<div>
<h1>Practical Node.js</h1>
<p>The only book most people will ever need.</p>
</div>
<div>
<footer>&copy; Apress</footer>
</div>
</body>


Its Jade syntax as given below:

Body
div
h1 Practical Node.js
p The only book most people will ever need.
div
footer &copy; Apress


  • Variables/Locals
h1= title
p= body

Locals:

{
title: "
Hello",
body: "
Jade Templaes"
}

HTML output:

<h1>Hello</h1>
<p>Jade Templaes</p>


  • Attributes
Attributes are added by putting them into parentheses right after the tag name. They follow name=value format.

div(id="content", class="main")
a(href="http://expressjsguide.com", title="Express.js Guide", target="_blank") Express.js Guide
form(action="/login")
button(type="submit, value="save")
div(class="hero-unit") Lean Node.js!



  •  Literals
 div#content
p.lead.center
| webapplog: where code lives
#side-bar.pull-right
span.contact.span4
a(href="/contact") contact us
<div id="content">
<p class="lead center">
webapplog: where code lives
<div id="side-bar" class="pull-right"></div>
<span class="contact span4">
<a href="/contact">contact us</a>
</span>
</p>
</div>


  •  Text
 div
| Jade is a template engine.
| It can be used in Node.js and in the browser JavaScript.



  •  Script and Style Blocks

 
script.
console.log('Hello Jade!')
setTimeout(function(){
window.location.href='http://rpjs.co'
},200))
console.log('Good bye!')
<script>
console.log('Hello Jade!')
setTimeout(function(){
window.location.href='http://rpjs.co'
},200))
console.log('Good bye!')
</script
>

  •  JavaScript Code
 - var arr = ['<a>','<b>','<c>']
ul
- for (var i = 0; i< arr.length; i++)
li
span= i
span!="unescaped: " + arr[i] + " vs. "
span= "escaped: " + arr[i]



produces this:

<ul>
<li><span>0</span><span>unescaped: <a> vs. </span><span>escaped: &lt;a&gt;</span></li>
<li><span>1</span><span>unescaped: <b> vs. </span><span>escaped: &lt;b&gt;</span></li>
<li><span>2</span><span>unescaped: <c> vs. </span><span>escaped: &lt;c&gt;</span></li>
</ul>



  •  Comments
 // content goes here
p Node.js

//- @todo change this to a class
p(id="footer") Copyright 2017


outputs

<!-- content goes here-->
<p>Node.js</p>
<p id="footer">Copyright 2017</p>



  •  Conditions (if )
- var user = {}
- user.admin = Math.random()>0.5
if user.admin
button(class="launch") Launch Spacecraft
else
button(class="login") Log in

There’s also unless, which is equivalent to not or !.


  •  Iterations (each loops)
 - var languages = ['php', 'node', 'ruby']
div
each value, index in languages
p= index + ". " + value


The HTML output is as follows:

<div>
<p>0. php</p>
<p>1. node</p>
<p>2. ruby</p>
</div>


if Key value in the array:

- var languages = {'php': -1, 'node': 2, 'ruby':1}
div
each value, key in languages
p= key + ": " + value

The Jade above is compiled into the HTML output:

<div>
<p>php: -1</p>
<p>node: 2</p>
<p>ruby: 1</p>
</div>


  •  Filters
Filters are used when there are blocks of texts written in a different language. For example, the filter for Markdown
looks like this:

p
:markdown
# Practical Node.js


  •  Interpolation
 Interpolation in Jade is achieved via #{name}. For example, to output title in a paragraph, do the following:

- var title = "Express.js Guide"
p Read the #{title} in PDF, MOBI and EPUB


  •  Case
 - var coins = Math.round(Math.random()*10)
case coins
when 0
p You have no money
when 1
p You have a coin
default
p You have #{coins} coins!


  •  Mixins
 Mixins are functions that take parameters and produce some HTML. The declaration syntax is mixin name(param,
param2,...), and the usage is +name(data)
. For example,

mixin row(items)
tr
each item, index in items
td= item

mixin table(tableData)
table
each row, index in tableData
+row(row)

- var node = [{name: "express"}, {name: "hapi"}, {name: "derby"}]
+table(node)
- var js = [{name: "backbone"}, {name: "angular"}, {name: "ember"}]
+table(js)

The template and data above produce this HTML:

<table>
<tr>
<td>express</td>
</tr>
<tr>
<td>hapi</td>
</tr>
<tr>
<td>derby</td>
</tr>
</table>
<table>
<tr>
<td>backbone</td>
</tr>
<tr>
<td>angular</td>

</tr>
<tr>
<td>ember</td>
</tr>
</table>


  • Include
 include is a way to split logic into a separate file for the purpose of reusing it across multiple files.

 include ../includes/footer

  •  Extend
 extend is a bottom-to-top approach (as oppose to include), in the sense that the included file commands which parts
of the main file it wants to replace.

In file_a:

block header
p some default text

block content
p Loading ...
block footer
p copyright


In file_b:

extend file_a
block header
p very specific text

block content
.main-content


  • Standalone use of  Jade - Jade sample use
 create the project folder named 'nodejs_jade_handlers' and run below commands:

it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_jade_handlers$ sudo npm init
it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_jade_handlers$ sudo npm install jade -save

 Once jade is installed, package.json will be as shown below:

{
  "name": "nodejs_jade_handlers",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "jade": "^1.11.0"
  }
}

 

 create my_jade.jade file and write below code

.header
h1= title
p
.body
p= body
.footer
div= By
a(href="http://abc.com/#{author.sachin4java}")= author.name


 
create my_jade.js file to call above jade template.

var jade = require('jade'),
fs = require('fs');
//this data will be sent to jade template
var data = {
title: "Learning Node.js",
author: {
sachin4java: "@http://sachin4java.blogspot.in",
name: "Sachin Rane"
},
tags: ['express', 'node', 'javascript']
}

//read jade template and show html on console

fs.readFile('my_jade.jade', 'utf-8', function(error, source){
var template = jade.compile(source); //jade template static
var html = template(data) //inject the data into template
console.log(html) //generated html
});



run the js file by below command:

it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_jade_handlers$ node my_jade.js

 output will be:




  •  Handlebars Syntax
 The Handlebars library is another template engine. Handlebars was made so that developers can’t write a lot of JavaScript logic inside the
templates.

A Handlebars expression is {{, some content, followed by }}, hence the name of the library (see the resemblance to
handlebars on a bicycle
)

 syntax:

<h1>{{title}}</h1>
<p>{{body}}</p>

with data:

{
title: "My Node js",
body: "Learning node js"
}

renders:

<h1>
My Node js</h1>
<p>
Learning node js</p>


  •  Iteration (each)
 <div>
{{#each languages}}
<p>{{@index}}. {{this}}</p>
{{/each}}
</div>

  •  Unescaped Output
Use - {{{ }}} for exscape characters 

{
arr: [
'<a>a</a>',
'<i>italic</i>',
'<strong>bold</strong>'
]
}


<ul>
{{#each arr}}
<li>
<span>{{@index}}</span>
<span>unescaped: {{{this}}} vs. </span>
<span>escaped: {{this}}</span>
</li>
{{/each}}
</ul>


  •  Conditions (if )
 {{#if user.admin}}
<button class="launch">Launch Spacecraft</button>
{{else}}
<button class="login"> Log in</button>
{{/if}}

populated with data:

{
user: {
admin: true
}
}


  • Unless
{{#unless user.admin}}


  • With
 In case there’s an object with nested properties, and there are a lot of them, it’s possible to use with to pass the context.


{{#with user}}
<p>{{name}}</p>
{{#with contact}}
<span>Twitter: @{{twitter}}</span>
{{/with}}
<span>Address: {{address.city}},
{{/with}}
{{user.address.state}}</span>



Data:
{user: {
contact: {
email: 'hi@azat.co',
twitter: 'azat_co'
},
address: {
city: 'San Francisco',
state: 'California'
},
name: 'Azat'
}}


  •  Comments
 To output comments, use regular HTML <!-- and -->. To hide comments in the final output, use {{! and }} or
{{!-- and --}}

 
<!-- content goes here -->
<p>Node.js is a non-blocking I/O for scalable apps.</p>
{{! @todo change this to a class}}
{{!-- add the example on {{#if}} --}}
<p id="footer">Copyright 2017</p>


Output:

<!-- content goes here -->
<p>Node.js is a non-blocking I/O for scalable apps.</p>
<p id="footer">Copyright 2017</p>


  • Custom Helpers
Custom Handlebars helpers are similar to built-in helper blocks and Jade mixins. To use custom helpers, we need to
create them as a JavaScript function and register them with the Handlebars instance.

Here goes the JavaScript/Node.js that tells the Handlebars compiler what to do when it encounters the custom
table function (i.e., print an HTML table out of the provided array):

Handlebars.registerHelper('table', function(data) {
var str = '<table>';
for (var i = 0; i < data.length; i++ ) {
str += '<tr>';
for (var key in data[i]) {
str += '<td>' + data[i][key] + '</td>';
};
str += '</tr>';
};
str += '</table>';

return new Handlebars.SafeString (str);
});


  •  Includes (Partials)
 Includes or partials templates in Handlebars are interpreted by the {{>partial_name}} expression. Partials are akin
to helpers and are registered with Handlebars.registerPartial(name, source), where name is a string and source is
a Handlebars template code for the partial.

  •  Standalone Handlebars Usage - Sample test demo
 install handlebars:

it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_jade_handlers$ sudo  npm install handlebars --save

 hanedlebars.js

var handlebars = require('handlebars'),
fs = require('fs');
//this data will be sent to handlebars template
var data = {
title: "learning node js", //intentionally given in small case to use with custom helper resgietred
author: {
sachin4java: "@http://sachin4java.blogspot.in",
name: "Sachin Rane"
},
tags: ['express', 'node', 'javascript']
}

//read jade template and show html on console

fs.readFile('hanedlebars.html', 'utf-8', function(error, source){
//register handle bar
   
handlebars.registerHelper('custom_title', function(title){
        var words = title.split(' ');
        for (var i = 0; i < words.length; i++) {
        if (words[i].length > 4) {
        words[i] = words[i][0].toUpperCase() + words[i].substr(1);
        }
        }
        title = words.join(' ');
        return title;
        })
   
   
var template = handlebars.compile(source);
var html = template(data) //inject the data into template
console.log(html) //generated html
});



hanedlebars.html

<div class="header">
<h1>{{custom_title title}}</h1>
</div>
<div class="body">
<p>{{body}}</p>
</div>
<div class="footer">
<div><a href="http://abc.com/{{author.sachin4java}}">{{autor.name}}</a>
</div>
<ul>
{{#each tags}}
<li>{{this}}</li>
{{/each}}
</ul>
</div>


Run with below command:

it000483@IND-PUN-LAP-183:~/vuclip/eclipse-workspace/nodejs_jade_handlers$ node handlebars.js

 output:

<div class="header">
<h1>Learning node js</h1>
</div>
<div class="body">
<p></p>
</div>
<div class="footer">
<div><a href="http://abc.com/@http://sachin4java.blogspot.in"></a>
</div>
<ul>
<li>express</li>
<li>node</li>
<li>javascript</li>
</ul>
</div>






No comments:

Post a Comment

Extract error records while inserting into db table using JDBCIO apache beam in java

 I was inserting data into postgres db using apache beam pipeline. it works perfectly with JdbcIO write of apache beam library. But, now, i ...