Taswar Bhatti
The synonyms of software simplicity
Jade

Jade Node.js Template Engine, Conditional Logic Statements

In my previous post I have talked about databinding with jade, i.e. feeding data to your template. In this post I will write about how one can use conditional and logical statements (for, if, while statements) in jade template engine.

Ternary Operation

The conditional ternary operator can be applied in Jade as follow ( ? : )

1
2
3
4
5
6
- time = "AM"
- greeting = (time == "AM") ? "Morning" : "Evening"
 
p Good #{greeting}
- var morning = false
body(class=morning?'AM':'PM')

Conditional Statements

Jade has built in (if, else statements, and also provides the unless statement)

1
2
3
4
5
6
7
8
9
10
- authorized = false
div
   if authorized
     p Welcome User
   else
     p User must login
 
div 
  unless authorized
    p You must login

Case statements

The case statement is more of a shorthand for the switch statement in Jade.

1
2
3
4
5
6
7
8
9
- input = 10
case input
  when 0
  when 1
    p input is 0 or 1
  when 10
    p input is 10
  default
    p input is #{input}

Iterators

Jade provides (for, each, while as loops)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//each statement
- list = ['a', 'b', 'c']
ul 
  each item in list
    li= item
 
//while loop
- index = 0
ul 
  while index < list.length
    li= list[index]
    - index++;
 
//for loop 
ul
  - for(var i = 0, len = list.length; i < len; i += 1) {
    li= list[i]
  - }

In my next post I will write about mixins and filters for Jade.

Jade

In my previous post I showed the basic syntax of jade when using express application in node.js, in this post I will go over the DataBinding aspects of jade template engine.

Jade Node.js Template Engine DataBinding through Interpolation

Jade provides interpolation of variables using the #{} syntax, Hash, Curly Brackets.
For example if we have a variable called name with a value of John, to display from our controller in Express Web Application in Node through jade, we will code it like

1
2
3
4
p Hello my name is #{name}
 
//output
<p>Hello my name is John</p>

We can also declare a variable inside the jade file, using the dash and var (although the var is optional), as the example shows below one can also access an array or hashtable like syntax.

1
2
3
4
5
6
7
8
9
10
11
12
13
- var name = "john"
p Hello my name is #{name}
 
- list = ['a', 'b', 'c']
p Lets learn the #{list[0]}, #{list[1]}, #{list[2]}
 
- items = {"name": "john", "age": "5" }
p #{items.name} is #{items.age} years old.
 
//output
<p>Hello my name is john</p>
<p>Lets learn the a, b, c</p> 
<p>John is 5 years old.</p>

Shortcuts

jade also provides a shortcut rather than using the interpolation syntax, by using just the “=” sign or by directly accessing the declared variables.

1
2
3
4
5
6
7
8
9
10
- lorem = "This is a sample lorem ipsum text, that isnt quite lorem ipsum"
 
p= lorem
 
- x = {"name": "john", "age": "5" }
 
input(type="text", name=x.name, value=x.age)
//output
<p>This is a sample lorem ipsum text, that isnt quite lorem ipsum</p>
<input type="text" name="john" value="5" />

How to escape HTML

Sometimes we have to escape html in a string, even though jade prevents us from XSS, we may come across a situation we a using a wysiwyg editor, that requires non encoded text.
Jade allows us to escape html by using the “!” syntax, for both shortcut and non shortcut curly brackets syntax.

1
2
3
4
5
6
7
8
- name = "Hello <b>John</b>"
p!= name
 
- test = "test <i>abc</i>"
p !{test}
//output 
<p>Hello <b>John</b></p>
<p>test <i>abc</i></p>

Hope you enjoy the series I will continue with our next blog with how to use filters and logic in Jade.

Jade

In my previous blog post I showed how one would install jade template engine for node.js and the terse markup that it provides. In this post I will continue on the jade and show the basic syntax of using jade template engine.

Basic syntax of Jade Template Engine for Node.js

As mentioned in earlier post, Jade is indentation-based, each level of indentation creates its own block. Thus the spaces are important/significant to it, also jade does not use end tags like html nor angle brackets. As we saw earlier in the p tag in our example.

Here is a simple example of h4 wrapped in span

1
2
 span
   h4
1
2
3
<span>
  <h4></h4>
</span>
   

In the next example if we removed the indentation we will not get h4 as the child of a span.

1
2
span
h4
1
2
<span></span>
<h4></h4>
   

The using of the | character can also signal for a textblock of text.

1
2
3
4
span
    | Hello
    br
    | world
1
2
3
4
5
<span>
      Hello
      <br />
      World
</span>
   

Jade also provides a shorthand for textblock rather than using all the pipe “|” character one can just add a period to the tag, and add additional html elements.

1
2
3
span.
    <u>Hello</u>    
    <b><i>world</i></b>
1
2
3
4
<span>
    <u>Hello</u>    
    <b><i>world</i></b>
</span>
   

Attributes

Attributes like class and id can be added by using the bracket sytanx to a tag, and multiple styles can be added with an array like syntax.

1
2
span(id="mySpanId", class="boldTheSpan") Hello World
span(class=['boldTheClass', 'italicClass', 'underlineClass']) Goodbye World
1
2
<span id="mySpanId" class="boldTheSpan">Hello World</span>
<span class="boldTheClass italicClass underlineClass">Goodbye World</span>
   

One can also pass in data as JSON for data-* attributes

1
span(data-sizes={options: ['small', 'large', 'xlarge']}) Hello World
1
<span data-sizes='{"options":["small","large","xlarge"]}'>Hello World</span>

Shortcuts

Here are some shortcuts of attributes for class and id when using jade, one can use the “#” for id and the period “.” of class right after the tag, and there is also automatic divs that jade provides

1
2
span#mySpanId.BoldClass Hello World
#myDiv Goodbye world
1
2
<span id="mySpanId" class="BoldClass">Hello World</span>
<div id="myDiv">Goodbye world</div>
   

Block expansion

Sometimes the indentation could becoming annoying when you are creating ordered or unordered list.

1
2
3
4
5
6
7
ol
  li 
    a(href="apple.html")Apple
  li.hightlight 
    a(href="orange.html")Orange
  li 
    a(href="pear.html")Pear

Jade has a solution to this since being terse is what jade is all about, it provides a “:” shortcut to simplify this for us.

1
2
3
4
ol
  li: a(href="apple.html")Apple
  li.highlight: a(href="orange.html")Orange
  li: a(href="pear.html")Pear

Comments and Block Comments

Jade also provides a way to comment out your template like the Javascript syntax it uses // and if you use // - it will not show the comment in the rendered html. It also provides a block syntax where if you indent the line after the comment it will comment out the following tags also.

1
2
3
4
// this is a comment
// - this will not show up in the render html
// comment out the tag below
  span#mySpanId.BoldClass Hello World
1
2
3
4
<!-- this is a comment -->
<!-- comment out the tag below
    <span id="mySpanId" class="BoldClass">Hello World</span>
-->
   

Summary

I have covered most of the basic syntax of Jade here in this blog post, in my next post I will write about how to bind data into the template.

Jade

Jade is a templating laguage for node.js, it provides an alternative syntax to write your HTML, some may say more pythonic or haml style. Jade by default comes with express web application framework for node.js

Lets take a look at a simple jade file compare it to your html file.
HTMLvs Jade

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h1>Hello world</h1>
    <p>
      This is a simple hello world example
    </p>
  </body>
</html>
1
2
3
4
5
6
7
doctype html
html
  head
  body
    h1 Hello world
    p.
      This is a simple hello world example

As one can see the jade syntax is more terse and concise, but one has to remember those spaces/indentation are quite important for jade.

Installing Jade

Jade by default comes with express web application for node.js, but one can also install it by npm.

?View Code SCRIPT
1
$ npm install jade

One can also compile and use jade with command line

?View Code SCRIPT
1
$ echo "p hello world" > helloworld.jade

To generate the html file we can run the jade command

?View Code SCRIPT
1
2
3
4
$ jade helloworld.jade
   rendered helloworld.html
$ cat helloworld.html
<p>hello world</p>

As we can see above it automatically create the angle tags for us for the paragraph tag.

In my next blog post I will be covering the basic syntax of jade

bower

Continuing on our previous blog post on bower, in this blog post, I will talk about how to create your own front-end packages in bower. One thing I forgot to mention in the previous post is git is required when using bower. If you are using windows you can install git for windows or Mac/Unix/Linux.

The very first thing one needs to do is create a bower.json file in your project root folder. By using the command below

?View Code SCRIPT
1
bower init

The above command will prompt you to fill in the form and afterwards it will generate us a bower.json file.
bower init

Lets take a look at our bower.json file

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
  "name": "JqueryLocaleListSort",
  "version": "0.0.1",
  "main": "./localeListSort.js"
  "description": "JavaScript list using locale sorting",
  "keywords": [
    "jquery",
    "plugin"
  ],
  "authors": [
    "Taswar Bhatti"
  ],
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ]
}

 

Adding Jquery

For our package, we will require jquery and in order to add our dependency to the bower.json file we can use the install command line. Note: the –save which will update our bower.json file, if we did not use the –save option it will not update out bower.json file.

?View Code SCRIPT
1
bower install jquery --save

Our bower.json file will now look like

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
{
  "name": "JqueryLocaleListSort",
  "version": "0.0.1",
  "main": "./localeListSort.js"
  "description": "Javascript sort of list using locale",
  "keywords": [
    "jquery",
    "plugin"
  ],
  "authors": [
    "Taswar Bhatti"
  ],
  "license": "MIT",
  "ignore": [
    "**/.*",
    "node_modules",
    "bower_components",
    "test",
    "tests"
  ],
  "dependencies": {
    "jquery": "~2.1.1"
  }
}

I will now use my previous jquery plugin that I created for sorting a list and add it to my project. The code is not really the focus here, it could be anything that you wish to publish, even a simple function of hello world.

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
(function ($) {
	$.fn.localeSort = function (options) {
		var settings = $.extend({}, $.fn.localeSort.defaults, options), $this = this;
 
		return this.each(function () {
			function sorty(list, compare, elem) {
		        elem = typeof elem !== 'undefined' ? elem : 'li';
 
				var listElements = list.find(elem);
 
				listElements.sort(compare);
 
				list.empty();
 
				listElements.each(function (index, li) {
					list.append(li);
				});
			}
 
			if (settings.ul === true) {
				sorty($this, settings.compare);
			}
		});
	};
 
	$.fn.localeSort.defaults = {
		ul: true,
		compare: function localeCompareSort(a, b) {
			var t1 = $(a),
				t2 = $(b);
			return t1.text().localeCompare(t2.text());
		}
	};
}(jQuery));

Next we will add a gitignore file so that we don’t push up the bower_components folder if we have any, also I will create a repo on github. Note: bower requires a version number by using the git tag in order for it to register your package.

?View Code SCRIPT
1
2
3
4
5
6
7
8
git init
git add *.json *.js .gitignore README.md
git commit -m "First version of my app"
git tag -a 0.0.1
git remote add origin https://github.com/username/RepoName.git
git push origin master 
 
bower register myPackageName git://github/username/RepoName.git

If you wish to modify your bower package, remember to update your tag version and bower.json file version or else it will not be published

?View Code SCRIPT
1
2
3
4
5
//modified js file and bower.json file update the version number
git commit -m "Second version of my app"
git tag -a 0.0.2
git remote add origin https://github.com/username/RepoName.git
git push origin master
bower

My last blog post was about using bower in node.js express application Visual Studio, and I believe I did not do justice to it. In this blog post I will talk more about how to use bower for your front-end and all the command line associate with bower.

Again to install bower globally one can use the npm command line

?View Code SCRIPT
1
npm install -g bower

To start using bower and to find packages e.g jquery, it will list out all the github repository that has jquery involved.

?View Code SCRIPT
1
bower search jquery

bowersearch

Installing Packages

To install latest jquery or by a version number we can append it with a “#” symbol like below, or by a git repo

?View Code SCRIPT
1
2
3
4
5
bower install jquery
 
bower install jquery#1.9.1
 
bower install git://github.com/pivotal/jasmine.git

In order to use jquery with bower on your site you can reference it in your html like

1
<script src="/bower_components/jquery/dist/jquery.min.js"></script>

Uninstall or Update a package

To uninstall or to upgrade a package e.g jquery

?View Code SCRIPT
1
2
3
bower upgrade jquery
 
bower uninstall jquery

To upgrade all installed packages one just needs to use

?View Code SCRIPT
1
bower upgrade

List installed packages

If one wants to find out what packages are installed in the solution one can use the command ls or list

?View Code SCRIPT
1
2
3
bower ls
or
bower list

bower ls

Information on a package

To find out information and version of a package that bower provides one can use the info command

?View Code SCRIPT
1
bower info jquery

bower info

One can also find out which repository bower is using for a package using the lookup command

?View Code SCRIPT
1
2
3
4
bower lookup jquery
 
Output:
jquery git://github.com/jquery/jquery.git

There is also the home command which takes you the homepage of the repository, the below command will take you the github repository of jquery

?View Code SCRIPT
1
bower home jquery

Caching

Bower has a caching where when you run the install it will automatically download the package to your ~/.bower/cache so that when you run install again it will just use the cache version for a quicker install, on windows you will find bower cache to be located at C:\Users\YourUsername\AppData\Roaming\bower\cache and on unix/linux systems in your home directory ~/.bower/cache

One can also clear the cache by using the command cache-clear.

?View Code SCRIPT
1
bower clear-cache

And last but not least there is also help command

?View Code SCRIPT
1
bower help

bower help

In my next blog I will write about how to create your own bower packages and all about bower.json file.

node.js

In my previous post I have shown how to create an express app with node.js and in this post, I would like to introduce bower a package manager for front-end development.

Bower is a package manager just like Nuget, where it gets confusing is that node already has a package manager called npm. The difference is that bower is more of a front end package manger, think of it as managing your jquery, angular, ember, etc.

So lets get bower installed using our Npm manager in Visual Studio, we will install it globally to our package manager, so that every project can use it. One can also install it using command line, where the -g means globally.

1
npm install -g bower

Right click on npm in your solution and Manage npm Modules…

bower

Once launched select the Global Packages Tab, and type bower in the package Name field and click on Install Globally.

install bower

The process will go through and npm Operation Completed Successfully is show on the npm window.

bower install npm

Node Tools for Visual Studio does not yet provide a way to use bower with the menu context, so in order to use bower one has to use a command prompt. I hope in the future they can provide a way to right click and say bower install etc.

We would need to right click on the project and select “Launch Command Prompt here

In the command prompt we install jquery, so we will type

1
bower install jquery

bower install jquery

By doing so you will find a new directory created in your solution called bower_components and it will pull the latest version of jquery into it.
bowervs

Jquery source installed
jquery bower

One can also install a specific version of package with bower by using the command

1
bower install jquery#1.9.1

To use jquery that we just installed with bower in our express app, we will need to edit the app,js file and add

?View Code JAVASCRIPT
1
app.use('/bower_components',  express.static(__dirname + '/bower_components'));

and you can then reference it in your html or layout file by

1
<script src="/bower_components/jquery/dist/jquery.min.js"></script>
jquery

I recently had to do work on localeCompare in JavaScript and though I would write a plugin in JQuery and share it.

Javascript Locale Compare

JavaScript provides a localeCompare function for comparing two strings in the current locale. The locale is based on the language settings of the browser. To explain locale compare lets look at some text.

?View Code JAVASCRIPT
1
2
3
4
5
var str1 = "apple",
    str2 = "orange",
    result = str.localeCompare(str2);
 
console.log(result);

Basically the function returns

  • -1 if the reference string is sorted before
  • 0 if the two strings are equal
  • 1 if the reference string is sorted after

Problem at hand

When we are localizing applications we tend to use some kind of resources key, in .NET we use resx files to localize an application. For example we may have 3 key, something like the image below
resx

In your code you may say something like

1
2
3
4
5
6
Sorted fruits
<ul id="mylist">
  <li><%= MyResource.AppleKey %></li>
  <li><%= MyResource.OrangeKey %></li>
  <li><%= MyResource.PearKey %></li>
</ul>

The output would display Apple, Orange and Pear and for English, the list is sorted properly, but if you translate those keys into french the sorting is incorrect, since in french Apple is Pomme. The display in French would be Pomme, Orange, Poire, which is incorrect. The sorting would also work for chinese 橙, 苹果, 梨.

In order to fix this I created a jquery plugin that would allow me to sort all unordered list

Below is the code for jquery plugin, I also have it on jsfiddle http://jsfiddle.net/taswar/bR9fZ/. One can also provide their own algorithm for compare, since if you are sorting a large amount of text, localeCompare may not be the most efficient algorithm and some browsers may implement it differently.

?View Code JAVASCRIPT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
(function ($) {
    $.fn.localeSort = function (options) {
        var settings = $.extend({}, $.fn.localeSort.defaults, options), $this = this;
 
        return this.each(function () {
            function sorty(list, compare, elem) {
		elem = typeof elem !== 'undefined' ? elem : 'li';
 
                var listElements = list.find(elem);
 
                listElements.sort(compare);
 
                list.empty();
 
                listElements.each(function (index, li) {
                    list.append(li);
                });
            }
 
            if (settings.ul === true) {
                sorty($this, settings.compare);
            }
        });
    };
 
    $.fn.localeSort.defaults = {
        ul: true,
        compare: function localeCompareSort(a, b) {
            var t1 = $(a),
                t2 = $(b);
            return t1.text().localeCompare(t2.text());
        }
    };
}(jQuery));
node.js

Here is a quick little tutorial of using Twitter Bootstrap with Node.js express in Visual Studio.

First we will create a ExpressBootstrap solution, select New Project and select JavaScript -> Blank Express Application.
bootstrap0

I will name my solution ExpressBootstrap, in my app.js I have also add the app.locals.appname = ‘Express Bootstrap’ so that I can reference it in my application.
bootstrap1

Next we will download and install bootstrap, this is the manual way of installing bootstrap, there is also an alternative by using bower, which I will cover in my next blog post.

One can download the latest bootstrap from http://getbootstrap.com/getting-started/#download
bootstrap2

Once downloaded lets grab the css, font and js directory and copy them into our public folder in our express application.

Next we will change our layout.jade file to use bootstrap

1
2
3
4
5
6
7
8
9
doctype html
head
    title= title
    link(rel='stylesheet', href='/css/bootstrap.min.css')
    link(rel='stylesheet', href='/stylesheets/style.css')
    script(src='http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js')
    script(src='/js/bootstrap.min.js')
  body
    block content

I will now add some style to the style.css found in stylesheet folder.

1
2
3
4
.wrapper {margin-top: 80px;margin-bottom: 80px;}
.form-signin{max-width:380px;padding:15px 35px 45px;margin:0 auto;background-color:#fff;border:1px solid rgba(0,0,0,.1);}
input[type="text"] {margin-bottom: -1px;border-bottom-left-radius: 0;border-bottom-right-radius: 0;}
input[type="password"] {margin-bottom: 20px;border-top-left-radius: 0;border-top-right-radius: 0;}

Now we will modify the index.jade file to present us with a bootstrap looking login page site.

1
2
3
4
5
6
7
8
9
10
extends layout
 
block content
	div.wrapper
		form.form-signin(method="post", id="loginForm")
			h2.form-signin-heading Please login
			input(class="form-control", id="username", type="text", name="User", placeholder="Enter your username")			
			input(class="form-control", id="password", type="password", name="Password", placeholder="Password")
			input(class="btn btn-lg btn-primary btn-block" type="submit", value="Log In")
	div.footer

One of the downside you may find with jade is the space vs tab issue, one cannot mix spaces and tabs with jade, sometimes it becomes annoying when you have trailing space with some text, that you may not realize.

The end result we will get something like
bootstrap3

linq

Here is a quick C# tip of counting up values of a Dictionary<TKey, TValue> where the values contains a List<T> using Linq.

Lets say you have a Dictionary that contains Dictionary<string, List<Guid>> and you wish to find out how many items of Guid you have.

You can easily do it by the Sum Linq aggregate operations

?View Code CSHARP
1
 int sum = dict.Sum(x => x.Value.Count);

This will tell you the amount of items you have in all the list.

And if you wish to just find out if there are any items in the list, rather than counting. For example you need to enable or disable a button on a UI, one can use the Linq Any quantifiers, it would be more efficient than the Sum Aggregate operator.

?View Code CSHARP
1
2
3
var hasItems = dict.Any(x => x.Value.Any());
 
MyButton.Enabled = hasItems;
UA-4524639-2