• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • JavaScript Templates: HandleBars.js and EJS

    Blogs20142014-03-28


    Handlebars and EJS are 2 popular JavaScript Templates, besides underscore template, jQuery-tmpl. They are very cool, Here are 2 my sample codes to use them properly.

    1. Handlebars JS

    Download resource ’handlebars-v1.3.0.js’ from its website, then write a ’index.html’ to do testing:

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Handlebars JavaScript Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script src="./handlebars-v1.3.0.js"></script>
    </head>
    <body>
    <script id="entry-template" type="text/x-handlebars-template">
      <div class="entry">
        <h1>{{title}}</h1>
        <div class="body">
          {{body}}
        </div>
      </div>
    </script>
    <script>
    $(function() {
    	var source   = $("#entry-template").html();
    	var template = Handlebars.compile(source);
    	var context = {title: "My New Post", body: "This is my first post!"}
    	var html    = template(context);
    	$('body').prepend(html);
    });
    </script>
    </body>
    </html>

    2. EJS JavaScript Template

    Download resource ’EJS package’ from its website, then write 2 html files: ’index.html’ and ’cleaning.ejs’ to do testing. Here is ’index.html‘:

    <!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>EJS JS Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <script type="text/javascript" src="./ejs.js"></script>
    <script type="text/javascript" src="./view.js"></script>
    </head>
    
    <body>
    <script>
    $(document).ready(function() {
    	var data = {
    		'title': 'Cleaning Supplies',
    		'supplies':
    			['mop',
    			'broom',
    			'duster']
    	};
    	// load the template file, then render it with data
    	var html = new EJS({url: 'cleaning.ejs'}).render(data);
    	$('body').append(html);
    });
    </script>
    </body>
    </html>

    Here is the template file ’cleaning.ejs‘:

    <ul>
    	<% for(var i=0; i<supplies.length; i++) { %>
    	<li>
    	    <%= link_to(supplies[i], 'supplies/'+supplies[i]) %>
    	</li>
    	<% } %>
    </ul>

    They both are pretty cool, especially useful in a customized MVC environment.