In the last chapter, you learned about Ember.js object-oriented design choices. In this chapter, you will learn about the Ember.js presentation layer. You will see how to use Handlebars.js, the default template processor in Ember.js.
In this chapter, we shall cover the following areas:
Traditionally, presentation template systems have been used mostly on the server side. Be it Jade, StringTemplate or any other template engine, they have helped us separate the business logic from the presentation logic. They have made our code more reusable, and easy to understand and test.
With a gradual shift in today's web application, more and more logic is now shifting from server side to client side. Single-page web applications are a perfect example of that. To give users a perfect immersive experience, single-page web applications handle most of the logic related to the user's interaction at client side.
One of the most common challenges faced in giving that immersive experience is how to gracefully update the UI of the application whenever the user interacts with it.
There are a quite a few ways of doing that. Let's see some of them:
functionupdateDom(data){ varlist = $("ul"); var comment = "<li><span>" + data.name + "</span>" + "<div>" + data.comment "</div></li>"; list.append(newComment); }
For small applications that have fewer presentation changes, this should be fine. But as the application grows, this makes the JavaScript code more and more complex and difficult to maintain.
<li> <p class="name">Hello This is {{ data.name }}</p> <p>I live at {{ data.address }}</p> </li>
The biggest advantage we got out of this approach is that we have now decoupled the data and the UI, to a large extent. The frontend developer can now work on the UI parallel, using plain HTML. They just need to add placeholders for the data to be displayed. The server responds in JSON and is agnostic to the UI that is consuming the data. The same response could be used by a mobile application to build its UI. Now, the only thing that we're left with is to implement the JavaScript, which replaces or binds the placeholders present in the templates with actual data.
Handlebars.js does what has just been mentioned in the third point and much more. Since today's ambitious web applications have much more complex UI and workflows, you would need a template engine that takes care of segregating the UI logic from the business logic of your application.
Harndlerbars.js is a semantic web template system, which was started in 2010 by Yahuda Katz. Handlebars.js is essentially a compiler that takes in the HTML with placeholders in it and outputs a JavaScript method. This compiled JavaScript method takes in argument for the data and returns the string containing your HTML with actual data. But all this is hidden from an end user and is taken care by the Ember.js framework in the backend. You just need to define the template with the correct convention and things should work fine.
3.15.151.32